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/managed_mode/managed_user_signin_manager_wrapper.h"
29 #include "chrome/browser/net/chrome_cookie_notification_details.h"
30 #include "chrome/browser/prefs/pref_service_syncable.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
33 #include "chrome/browser/signin/about_signin_internals.h"
34 #include "chrome/browser/signin/about_signin_internals_factory.h"
35 #include "chrome/browser/signin/profile_oauth2_token_service.h"
36 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
37 #include "chrome/browser/signin/signin_manager.h"
38 #include "chrome/browser/signin/signin_manager_factory.h"
39 #include "chrome/browser/sync/backend_migrator.h"
40 #include "chrome/browser/sync/glue/change_processor.h"
41 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.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/ui/browser.h"
56 #include "chrome/browser/ui/browser_list.h"
57 #include "chrome/browser/ui/browser_window.h"
58 #include "chrome/browser/ui/global_error/global_error_service.h"
59 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
60 #include "chrome/common/chrome_switches.h"
61 #include "chrome/common/chrome_version_info.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/url_constants.h"
64 #include "components/sync_driver/data_type_controller.h"
65 #include "components/sync_driver/system_encryptor.h"
66 #include "components/sync_driver/user_selectable_sync_type.h"
67 #include "components/user_prefs/pref_registry_syncable.h"
68 #include "content/public/browser/notification_details.h"
69 #include "content/public/browser/notification_service.h"
70 #include "content/public/browser/notification_source.h"
71 #include "google_apis/gaia/gaia_constants.h"
72 #include "grit/generated_resources.h"
73 #include "net/cookies/cookie_monster.h"
74 #include "net/url_request/url_request_context_getter.h"
75 #include "sync/api/sync_error.h"
76 #include "sync/internal_api/public/configure_reason.h"
77 #include "sync/internal_api/public/http_bridge_network_resources.h"
78 #include "sync/internal_api/public/network_resources.h"
79 #include "sync/internal_api/public/sync_encryption_handler.h"
80 #include "sync/internal_api/public/util/experiments.h"
81 #include "sync/internal_api/public/util/sync_string_conversions.h"
82 #include "sync/js/js_arg_list.h"
83 #include "sync/js/js_event_details.h"
84 #include "sync/util/cryptographer.h"
85 #include "ui/base/l10n/l10n_util.h"
86 #include "ui/base/l10n/time_format.h"
88 #if defined(ENABLE_MANAGED_USERS)
89 #include "chrome/browser/managed_mode/managed_user_constants.h"
92 #if defined(OS_ANDROID)
93 #include "sync/internal_api/public/read_transaction.h"
96 using browser_sync::ChangeProcessor
;
97 using browser_sync::DataTypeController
;
98 using browser_sync::DataTypeManager
;
99 using browser_sync::FailedDataTypesHandler
;
100 using browser_sync::NotificationServiceSessionsRouter
;
101 using browser_sync::SyncBackendHost
;
102 using syncer::ModelType
;
103 using syncer::ModelTypeSet
;
104 using syncer::JsBackend
;
105 using syncer::JsController
;
106 using syncer::JsEventDetails
;
107 using syncer::JsEventHandler
;
108 using syncer::ModelSafeRoutingInfo
;
109 using syncer::SyncCredentials
;
110 using syncer::SyncProtocolError
;
111 using syncer::WeakHandle
;
113 typedef GoogleServiceAuthError AuthError
;
115 const char* ProfileSyncService::kSyncServerUrl
=
116 "https://clients4.google.com/chrome-sync";
118 const char* ProfileSyncService::kDevServerUrl
=
119 "https://clients4.google.com/chrome-sync/dev";
121 const char kSyncUnrecoverableErrorHistogram
[] =
122 "Sync.UnrecoverableErrors";
124 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
125 // Number of initial errors (in sequence) to ignore before applying
126 // exponential back-off rules.
129 // Initial delay for exponential back-off in ms.
132 // Factor by which the waiting time will be multiplied.
135 // Fuzzing percentage. ex: 10% will spread requests randomly
136 // between 90%-100% of the calculated time.
139 // Maximum amount of time we are willing to delay our request in ms.
140 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
141 // RequestAccessToken on connection state change after backoff
142 1000 * 3600 * 4, // 4 hours.
144 // Time to keep an entry from being discarded even when it
145 // has no significant state, -1 to never discard.
148 // Don't use initial delay unless the last request was an error.
152 bool ShouldShowActionOnUI(
153 const syncer::SyncProtocolError
& error
) {
154 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
155 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
156 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
159 ProfileSyncService::ProfileSyncService(
160 ProfileSyncComponentsFactory
* factory
,
162 ManagedUserSigninManagerWrapper
* signin_wrapper
,
163 ProfileOAuth2TokenService
* oauth2_token_service
,
164 StartBehavior start_behavior
)
165 : OAuth2TokenService::Consumer("sync"),
166 last_auth_error_(AuthError::AuthErrorNone()),
167 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
170 sync_prefs_(profile_
->GetPrefs()),
171 sync_service_url_(kDevServerUrl
),
172 data_type_requested_sync_startup_(false),
173 is_first_time_sync_configure_(false),
174 backend_initialized_(false),
175 sync_disabled_by_admin_(false),
176 is_auth_in_progress_(false),
177 signin_(signin_wrapper
),
178 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
179 expect_sync_configuration_aborted_(false),
180 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
181 encrypt_everything_(false),
182 encryption_pending_(false),
183 auto_start_enabled_(start_behavior
== AUTO_START
),
184 configure_status_(DataTypeManager::UNKNOWN
),
185 setup_in_progress_(false),
186 oauth2_token_service_(oauth2_token_service
),
187 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
189 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
190 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
191 network_resources_(new syncer::HttpBridgeNetworkResources
) {
193 // By default, dev, canary, and unbranded Chromium users will go to the
194 // development servers. Development servers have more features than standard
195 // sync servers. Users with officially-branded Chrome stable and beta builds
196 // will go to the standard sync servers.
198 // GetChannel hits the registry on Windows. See http://crbug.com/70380.
199 base::ThreadRestrictions::ScopedAllowIO allow_io
;
200 chrome::VersionInfo::Channel channel
= chrome::VersionInfo::GetChannel();
201 if (channel
== chrome::VersionInfo::CHANNEL_STABLE
||
202 channel
== chrome::VersionInfo::CHANNEL_BETA
) {
203 sync_service_url_
= GURL(kSyncServerUrl
);
206 if (!CommandLine::ForCurrentProcess()->HasSwitch(
207 switches::kDisableSyncSessionsV2
)) {
208 syncer::SyncableService::StartSyncFlare
flare(
209 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
210 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
211 new NotificationServiceSessionsRouter(profile
, flare
));
212 sessions_sync_manager_
.reset(
213 new SessionsSyncManager(profile
, this, router
.Pass()));
217 ProfileSyncService::~ProfileSyncService() {
218 sync_prefs_
.RemoveSyncPrefObserver(this);
219 // Shutdown() should have been called before destruction.
220 CHECK(!backend_initialized_
);
223 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
224 // Exit if sync is disabled.
225 if (IsManaged() || sync_prefs_
.IsStartSuppressed())
228 // Sync is logged in if there is a non-empty effective username.
229 return !signin_
->GetEffectiveUsername().empty();
232 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
233 if (!oauth2_token_service_
)
236 return oauth2_token_service_
->RefreshTokenIsAvailable(
237 signin_
->GetAccountIdToUse());
240 void ProfileSyncService::Initialize() {
243 // We clear this here (vs Shutdown) because we want to remember that an error
244 // happened on shutdown so we can display details (message, location) about it
248 sync_prefs_
.AddSyncPrefObserver(this);
250 // For now, the only thing we can do through policy is to turn sync off.
256 RegisterAuthNotifications();
258 if (!HasSyncSetupCompleted() || signin_
->GetEffectiveUsername().empty()) {
259 // Clean up in case of previous crash / setup abort / signout.
263 TrySyncDatatypePrefRecovery();
265 last_synced_time_
= sync_prefs_
.GetLastSyncedTime();
267 #if defined(OS_CHROMEOS)
268 std::string bootstrap_token
= sync_prefs_
.GetEncryptionBootstrapToken();
269 if (bootstrap_token
.empty()) {
270 sync_prefs_
.SetEncryptionBootstrapToken(
271 sync_prefs_
.GetSpareBootstrapToken());
275 #if !defined(OS_ANDROID)
276 if (!sync_global_error_
) {
277 sync_global_error_
.reset(new SyncGlobalError(this, signin()));
278 GlobalErrorServiceFactory::GetForProfile(profile_
)->AddGlobalError(
279 sync_global_error_
.get());
280 AddObserver(sync_global_error_
.get());
287 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
288 DCHECK(!sync_initialized());
289 if (!HasSyncSetupCompleted())
292 // There was a bug where OnUserChoseDatatypes was not properly called on
293 // configuration (see crbug.com/154940). We detect this by checking whether
294 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
295 // completed, it means sync was not properly configured, so we manually
296 // set kSyncKeepEverythingSynced.
297 PrefService
* const pref_service
= profile_
->GetPrefs();
300 if (GetPreferredDataTypes().Size() > 1)
303 const PrefService::Preference
* keep_everything_synced
=
304 pref_service
->FindPreference(prefs::kSyncKeepEverythingSynced
);
305 // This will be false if the preference was properly set or if it's controlled
307 if (!keep_everything_synced
->IsDefaultValue())
310 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
311 // types now, before we configure.
312 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
313 sync_prefs_
.SetKeepEverythingSynced(true);
314 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
315 sync_prefs_
.SetPreferredDataTypes(registered_types
,
319 void ProfileSyncService::TryStart() {
320 if (!IsSyncEnabledAndLoggedIn())
323 // Don't start sync until tokens are loaded, because the user can be
324 // "signed in" long before the tokens get loaded, and we don't want to
325 // generate spurious auth errors.
326 if (!IsOAuthRefreshTokenAvailable())
329 // If we got here then tokens are loaded and user logged in and sync is
330 // enabled. If OAuth refresh token is not available then something is wrong.
331 // When PSS requests access token, OAuth2TokenService will return error and
332 // PSS will show error to user asking to reauthenticate.
333 UMA_HISTOGRAM_BOOLEAN("Sync.RefreshTokenAvailable",
334 IsOAuthRefreshTokenAvailable());
336 // If sync setup has completed we always start the backend. If the user is in
337 // the process of setting up now, we should start the backend to download
338 // account control state / encryption information). If autostart is enabled,
339 // but we haven't completed sync setup, we try to start sync anyway, since
340 // it's possible we crashed/shutdown after logging in but before the backend
341 // finished initializing the last time.
343 // However, the only time we actually need to start sync _immediately_ is if
344 // we haven't completed sync setup and the user is in the process of setting
345 // up - either they just signed in (for the first time) on an auto-start
346 // platform or they explicitly kicked off sync setup, and e.g we need to
347 // fetch account details like encryption state to populate UI. Otherwise,
348 // for performance reasons and maximizing parallelism at chrome startup, we
349 // defer the heavy lifting for sync init until things have calmed down.
350 if (HasSyncSetupCompleted()) {
351 if (!data_type_requested_sync_startup_
)
352 StartUp(STARTUP_BACKEND_DEFERRED
);
353 else if (start_up_time_
.is_null())
354 StartUp(STARTUP_IMMEDIATE
);
356 StartUpSlowBackendComponents();
357 } else if (setup_in_progress_
|| auto_start_enabled_
) {
358 // We haven't completed sync setup. Start immediately if the user explicitly
359 // kicked this off or we're supposed to automatically start syncing.
360 StartUp(STARTUP_IMMEDIATE
);
364 void ProfileSyncService::StartSyncingWithServer() {
366 backend_
->StartSyncingWithServer();
369 void ProfileSyncService::RegisterAuthNotifications() {
370 oauth2_token_service_
->AddObserver(this);
373 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
374 content::Source
<Profile
>(profile_
));
376 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT
,
377 content::Source
<Profile
>(profile_
));
380 void ProfileSyncService::UnregisterAuthNotifications() {
381 oauth2_token_service_
->RemoveObserver(this);
382 registrar_
.RemoveAll();
385 void ProfileSyncService::RegisterDataTypeController(
386 DataTypeController
* data_type_controller
) {
387 DCHECK_EQ(data_type_controllers_
.count(data_type_controller
->type()), 0U);
388 data_type_controllers_
[data_type_controller
->type()] =
389 data_type_controller
;
392 browser_sync::SessionModelAssociator
*
393 ProfileSyncService::GetSessionModelAssociatorDeprecated() {
394 if (!IsSessionsDataTypeControllerRunning())
397 // If we're using sessions V2, there's no model associator.
398 if (sessions_sync_manager_
.get())
401 return static_cast<browser_sync::SessionDataTypeController
*>(
402 data_type_controllers_
.find(
403 syncer::SESSIONS
)->second
.get())->GetModelAssociator();
406 bool ProfileSyncService::IsSessionsDataTypeControllerRunning() const {
407 return data_type_controllers_
.find(syncer::SESSIONS
) !=
408 data_type_controllers_
.end() &&
409 data_type_controllers_
.find(syncer::SESSIONS
)->second
->state() ==
410 DataTypeController::RUNNING
;
413 browser_sync::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
414 if (!IsSessionsDataTypeControllerRunning())
417 if (!CommandLine::ForCurrentProcess()->HasSwitch(
418 switches::kDisableSyncSessionsV2
)) {
419 return sessions_sync_manager_
.get();
421 return GetSessionModelAssociatorDeprecated();
425 browser_sync::FaviconCache
* ProfileSyncService::GetFaviconCache() {
426 // TODO(tim): Clean this up (or remove) once there's only one implementation.
428 if (!CommandLine::ForCurrentProcess()->HasSwitch(
429 switches::kDisableSyncSessionsV2
)) {
430 return sessions_sync_manager_
->GetFaviconCache();
431 } else if (GetSessionModelAssociatorDeprecated()) {
432 return GetSessionModelAssociatorDeprecated()->GetFaviconCache();
438 scoped_ptr
<browser_sync::DeviceInfo
>
439 ProfileSyncService::GetLocalDeviceInfo() const {
441 browser_sync::SyncedDeviceTracker
* device_tracker
=
442 backend_
->GetSyncedDeviceTracker();
444 return device_tracker
->ReadLocalDeviceInfo();
446 return scoped_ptr
<browser_sync::DeviceInfo
>();
449 scoped_ptr
<browser_sync::DeviceInfo
>
450 ProfileSyncService::GetDeviceInfo(const std::string
& client_id
) const {
452 browser_sync::SyncedDeviceTracker
* device_tracker
=
453 backend_
->GetSyncedDeviceTracker();
455 return device_tracker
->ReadDeviceInfo(client_id
);
457 return scoped_ptr
<browser_sync::DeviceInfo
>();
460 ScopedVector
<browser_sync::DeviceInfo
>
461 ProfileSyncService::GetAllSignedInDevices() const {
462 ScopedVector
<browser_sync::DeviceInfo
> devices
;
464 browser_sync::SyncedDeviceTracker
* device_tracker
=
465 backend_
->GetSyncedDeviceTracker();
466 if (device_tracker
) {
467 // TODO(lipalani) - Make device tracker return a scoped vector.
468 device_tracker
->GetAllSyncedDeviceInfo(&devices
);
471 return devices
.Pass();
474 std::string
ProfileSyncService::GetLocalSyncCacheGUID() const {
476 browser_sync::SyncedDeviceTracker
* device_tracker
=
477 backend_
->GetSyncedDeviceTracker();
478 if (device_tracker
) {
479 return device_tracker
->cache_guid();
482 return std::string();
485 // Notifies the observer of any device info changes.
486 void ProfileSyncService::AddObserverForDeviceInfoChange(
487 browser_sync::SyncedDeviceTracker::Observer
* observer
) {
489 browser_sync::SyncedDeviceTracker
* device_tracker
=
490 backend_
->GetSyncedDeviceTracker();
491 if (device_tracker
) {
492 device_tracker
->AddObserver(observer
);
497 // Removes the observer from device info change notification.
498 void ProfileSyncService::RemoveObserverForDeviceInfoChange(
499 browser_sync::SyncedDeviceTracker::Observer
* observer
) {
501 browser_sync::SyncedDeviceTracker
* device_tracker
=
502 backend_
->GetSyncedDeviceTracker();
503 if (device_tracker
) {
504 device_tracker
->RemoveObserver(observer
);
509 void ProfileSyncService::GetDataTypeControllerStates(
510 browser_sync::DataTypeController::StateMap
* state_map
) const {
511 for (browser_sync::DataTypeController::TypeMap::const_iterator iter
=
512 data_type_controllers_
.begin(); iter
!= data_type_controllers_
.end();
514 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
517 void ProfileSyncService::InitSettings() {
518 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
520 // Override the sync server URL from the command-line, if sync server
521 // command-line argument exists.
522 if (command_line
.HasSwitch(switches::kSyncServiceURL
)) {
523 std::string
value(command_line
.GetSwitchValueASCII(
524 switches::kSyncServiceURL
));
525 if (!value
.empty()) {
526 GURL
custom_sync_url(value
);
527 if (custom_sync_url
.is_valid()) {
528 sync_service_url_
= custom_sync_url
;
530 LOG(WARNING
) << "The following sync URL specified at the command-line "
531 << "is invalid: " << value
;
537 SyncCredentials
ProfileSyncService::GetCredentials() {
538 SyncCredentials credentials
;
539 credentials
.email
= signin_
->GetEffectiveUsername();
540 DCHECK(!credentials
.email
.empty());
541 credentials
.sync_token
= access_token_
;
543 if (credentials
.sync_token
.empty())
544 credentials
.sync_token
= "credentials_lost";
548 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
554 SyncCredentials credentials
= GetCredentials();
556 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
557 profile_
->GetRequestContext());
559 if (delete_stale_data
)
562 scoped_ptr
<syncer::UnrecoverableErrorHandler
>
563 backend_unrecoverable_error_handler(
564 new browser_sync::BackendUnrecoverableErrorHandler(
565 MakeWeakHandle(weak_factory_
.GetWeakPtr())));
567 backend_
->Initialize(
574 scoped_ptr
<syncer::SyncManagerFactory
>(
575 new syncer::SyncManagerFactory
).Pass(),
576 backend_unrecoverable_error_handler
.Pass(),
577 &browser_sync::ChromeReportUnrecoverableError
,
578 network_resources_
.get());
581 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
582 if (encryption_pending())
584 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
585 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
586 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
587 return !Intersection(preferred_types
, encrypted_types
).Empty();
590 void ProfileSyncService::OnSyncConfigureRetry() {
591 // Note: in order to handle auth failures that arise before the backend is
592 // initialized (e.g. from invalidation notifier, or downloading new control
593 // types), we have to gracefully handle configuration retries at all times.
594 // At this point an auth error badge should be shown, which once resolved
595 // will trigger a new sync cycle.
599 void ProfileSyncService::StartUp(StartUpDeferredOption deferred_option
) {
600 // Don't start up multiple times.
602 DVLOG(1) << "Skipping bringing up backend host.";
606 DCHECK(IsSyncEnabledAndLoggedIn());
608 if (start_up_time_
.is_null()) {
609 start_up_time_
= base::Time::Now();
611 // We don't care to prevent multiple calls to StartUp in deferred mode
612 // because it's fast and has no side effects.
613 DCHECK_EQ(STARTUP_BACKEND_DEFERRED
, deferred_option
);
616 if (deferred_option
== STARTUP_BACKEND_DEFERRED
&&
617 CommandLine::ForCurrentProcess()->
618 HasSwitch(switches::kSyncEnableDeferredStartup
)) {
622 StartUpSlowBackendComponents();
625 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
626 syncer::ModelType type
) {
627 DCHECK(syncer::UserTypes().Has(type
));
628 if (backend_
.get()) {
629 DVLOG(1) << "A data type requested sync startup, but it looks like "
630 "something else beat it to the punch.";
634 if (!GetActiveDataTypes().Has(type
)) {
635 // We can get here as datatype SyncableServices are typically wired up
636 // to the native datatype even if sync isn't enabled.
637 DVLOG(1) << "Dropping sync startup request because type "
638 << syncer::ModelTypeToString(type
) << "not enabled.";
642 if (CommandLine::ForCurrentProcess()->HasSwitch(
643 switches::kSyncEnableDeferredStartup
)) {
644 DVLOG(2) << "Data type requesting sync startup: "
645 << syncer::ModelTypeToString(type
);
646 // Measure the time spent waiting for init and the type that triggered it.
647 // We could measure the time spent deferred on a per-datatype basis, but
648 // for now this is probably sufficient.
649 if (!start_up_time_
.is_null()) {
650 // TODO(tim): Cache |type| and move this tracking to StartUp. I'd like
651 // to pull all the complicated init logic and state out of
652 // ProfileSyncService and have only a StartUp method, though. One step
653 // at a time. Bug 80149.
654 base::TimeDelta time_deferred
= base::Time::Now() - start_up_time_
;
655 UMA_HISTOGRAM_TIMES("Sync.Startup.TimeDeferred", time_deferred
);
656 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.TypeTriggeringInit",
657 ModelTypeToHistogramInt(type
),
658 syncer::MODEL_TYPE_COUNT
);
660 data_type_requested_sync_startup_
= true;
663 DVLOG(2) << "Ignoring data type request for sync startup: "
664 << syncer::ModelTypeToString(type
);
667 void ProfileSyncService::StartUpSlowBackendComponents() {
668 // Don't start up multiple times.
670 DVLOG(1) << "Skipping bringing up backend host.";
674 DCHECK(IsSyncEnabledAndLoggedIn());
676 factory_
->CreateSyncBackendHost(
677 profile_
->GetDebugName(),
679 sync_prefs_
.AsWeakPtr()));
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
== signin_
->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
) {
794 if (sync_global_error_
) {
795 GlobalErrorServiceFactory::GetForProfile(profile_
)->RemoveGlobalError(
796 sync_global_error_
.get());
797 RemoveObserver(sync_global_error_
.get());
798 sync_global_error_
.reset(NULL
);
804 // First, we spin down the backend to stop change processing as soon as
806 base::Time shutdown_start_time
= base::Time::Now();
807 backend_
->StopSyncingForShutdown();
809 // Stop all data type controllers, if needed. Note that until Stop
810 // completes, it is possible in theory to have a ChangeProcessor apply a
811 // change from a native model. In that case, it will get applied to the sync
812 // database (which doesn't get destroyed until we destroy the backend below)
813 // as an unsynced change. That will be persisted, and committed on restart.
814 if (data_type_manager_
) {
815 if (data_type_manager_
->state() != DataTypeManager::STOPPED
) {
816 // When aborting as part of shutdown, we should expect an aborted sync
817 // configure result, else we'll dcheck when we try to read the sync error.
818 expect_sync_configuration_aborted_
= true;
819 data_type_manager_
->Stop();
821 data_type_manager_
.reset();
824 // Shutdown the migrator before the backend to ensure it doesn't pull a null
827 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
829 // Move aside the backend so nobody else tries to use it while we are
831 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
832 if (doomed_backend
) {
833 sync_thread_
= doomed_backend
->Shutdown(option
);
834 doomed_backend
.reset();
836 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
837 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
839 weak_factory_
.InvalidateWeakPtrs();
841 // Clear various flags.
842 start_up_time_
= base::Time();
843 expect_sync_configuration_aborted_
= false;
844 is_auth_in_progress_
= false;
845 backend_initialized_
= false;
846 cached_passphrase_
.clear();
847 access_token_
.clear();
848 encryption_pending_
= false;
849 encrypt_everything_
= false;
850 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
851 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
852 request_access_token_retry_timer_
.Stop();
853 // Revert to "no auth error".
854 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
855 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
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 current_experiments_
= experiments
;
1084 // Handle preference-backed experiments first.
1085 if (experiments
.gcm_channel_state
!= syncer::Experiments::UNSET
) {
1086 profile()->GetPrefs()->SetBoolean(prefs::kGCMChannelEnabled
,
1087 experiments
.gcm_channel_state
==
1088 syncer::Experiments::ENABLED
);
1089 gcm::GCMProfileServiceFactory::GetForProfile(profile());
1092 if (experiments
.enhanced_bookmarks_enabled
) {
1093 profile_
->GetPrefs()->SetBoolean(prefs::kEnhancedBookmarksExperimentEnabled
,
1095 profile_
->GetPrefs()->SetString(prefs::kEnhancedBookmarksExtensionId
,
1096 experiments
.enhanced_bookmarks_ext_id
);
1099 // If this is a first time sync for a client, this will be called before
1100 // OnBackendInitialized() to ensure the new datatypes are available at sync
1101 // setup. As a result, the migrator won't exist yet. This is fine because for
1102 // first time sync cases we're only concerned with making the datatype
1104 if (migrator_
.get() &&
1105 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1106 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1110 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1111 syncer::ModelTypeSet to_add
;
1112 const syncer::ModelTypeSet to_register
=
1113 Difference(to_add
, registered_types
);
1114 DVLOG(2) << "OnExperimentsChanged called with types: "
1115 << syncer::ModelTypeSetToString(to_add
);
1116 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register
);
1118 for (syncer::ModelTypeSet::Iterator it
= to_register
.First();
1119 it
.Good(); it
.Inc()) {
1120 // Received notice to enable experimental type. Check if the type is
1121 // registered, and if not register a new datatype controller.
1122 RegisterNewDataType(it
.Get());
1125 // Check if the user has "Keep Everything Synced" enabled. If so, we want
1126 // to turn on all experimental types if they're not already on. Otherwise we
1128 // Note: if any types are already registered, we don't turn them on. This
1129 // covers the case where we're already in the process of reconfiguring
1130 // to turn an experimental type on.
1131 if (sync_prefs_
.HasKeepEverythingSynced()) {
1132 // Mark all data types as preferred.
1133 sync_prefs_
.SetPreferredDataTypes(registered_types
, registered_types
);
1135 // Only automatically turn on types if we have already finished set up.
1136 // Otherwise, just leave the experimental types on by default.
1137 if (!to_register
.Empty() && HasSyncSetupCompleted() && migrator_
) {
1138 DVLOG(1) << "Dynamically enabling new datatypes: "
1139 << syncer::ModelTypeSetToString(to_register
);
1140 OnMigrationNeededForTypes(to_register
);
1145 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1146 is_auth_in_progress_
= false;
1147 last_auth_error_
= error
;
1154 AuthError
ConnectionStatusToAuthError(
1155 syncer::ConnectionStatus status
) {
1157 case syncer::CONNECTION_OK
:
1158 return AuthError::AuthErrorNone();
1160 case syncer::CONNECTION_AUTH_ERROR
:
1161 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1163 case syncer::CONNECTION_SERVER_ERROR
:
1164 return AuthError(AuthError::CONNECTION_FAILED
);
1168 return AuthError(AuthError::CONNECTION_FAILED
);
1174 void ProfileSyncService::OnConnectionStatusChange(
1175 syncer::ConnectionStatus status
) {
1176 connection_status_update_time_
= base::Time::Now();
1177 connection_status_
= status
;
1178 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1179 // Sync server returned error indicating that access token is invalid. It
1180 // could be either expired or access is revoked. Let's request another
1181 // access token and if access is revoked then request for token will fail
1182 // with corresponding error. If access token is repeatedly reported
1183 // invalid, there may be some issues with server, e.g. authentication
1184 // state is inconsistent on sync and token server. In that case, we
1185 // backoff token requests exponentially to avoid hammering token server
1186 // too much and to avoid getting same token due to token server's caching
1187 // policy. |request_access_token_retry_timer_| is used to backoff request
1188 // triggered by both auth error and failure talking to GAIA server.
1189 // Therefore, we're likely to reach the backoff ceiling more quickly than
1190 // you would expect from looking at the BackoffPolicy if both types of
1191 // errors happen. We shouldn't receive two errors back-to-back without
1192 // attempting a token/sync request in between, thus crank up request delay
1193 // unnecessary. This is because we won't make a sync request if we hit an
1194 // error until GAIA succeeds at sending a new token, and we won't request
1195 // a new token unless sync reports a token failure. But to be safe, don't
1196 // schedule request if this happens.
1197 if (request_access_token_retry_timer_
.IsRunning()) {
1199 } else if (request_access_token_backoff_
.failure_count() == 0) {
1200 // First time request without delay. Currently invalid token is used
1201 // to initialize sync backend and we'll always end up here. We don't
1202 // want to delay initialization.
1203 request_access_token_backoff_
.InformOfRequest(false);
1204 RequestAccessToken();
1206 request_access_token_backoff_
.InformOfRequest(false);
1207 request_access_token_retry_timer_
.Start(
1209 request_access_token_backoff_
.GetTimeUntilRelease(),
1210 base::Bind(&ProfileSyncService::RequestAccessToken
,
1211 weak_factory_
.GetWeakPtr()));
1214 // Reset backoff time after successful connection.
1215 if (status
== syncer::CONNECTION_OK
) {
1216 // Request shouldn't be scheduled at this time. But if it is, it's
1217 // possible that sync flips between OK and auth error states rapidly,
1218 // thus hammers token server. To be safe, only reset backoff delay when
1219 // no scheduled request.
1220 if (request_access_token_retry_timer_
.IsRunning()) {
1223 request_access_token_backoff_
.Reset();
1227 const GoogleServiceAuthError auth_error
=
1228 ConnectionStatusToAuthError(status
);
1229 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1230 UpdateAuthErrorState(auth_error
);
1234 void ProfileSyncService::StopSyncingPermanently() {
1235 sync_prefs_
.SetStartSuppressed(true);
1239 void ProfileSyncService::OnPassphraseRequired(
1240 syncer::PassphraseRequiredReason reason
,
1241 const sync_pb::EncryptedData
& pending_keys
) {
1242 DCHECK(backend_
.get());
1243 DCHECK(backend_
->IsNigoriEnabled());
1245 // TODO(lipalani) : add this check to other locations as well.
1246 if (HasUnrecoverableError()) {
1247 // When unrecoverable error is detected we post a task to shutdown the
1248 // backend. The task might not have executed yet.
1252 DVLOG(1) << "Passphrase required with reason: "
1253 << syncer::PassphraseRequiredReasonToString(reason
);
1254 passphrase_required_reason_
= reason
;
1256 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1257 if (data_type_manager_
) {
1258 // Reconfigure without the encrypted types (excluded implicitly via the
1259 // failed datatypes handler).
1260 data_type_manager_
->Configure(types
,
1261 syncer::CONFIGURE_REASON_CRYPTO
);
1264 // Notify observers that the passphrase status may have changed.
1268 void ProfileSyncService::OnPassphraseAccepted() {
1269 DVLOG(1) << "Received OnPassphraseAccepted.";
1271 // If the pending keys were resolved via keystore, it's possible we never
1272 // consumed our cached passphrase. Clear it now.
1273 if (!cached_passphrase_
.empty())
1274 cached_passphrase_
.clear();
1276 // Reset passphrase_required_reason_ since we know we no longer require the
1277 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1278 // because that can be called by OnPassphraseRequired() if no encrypted data
1279 // types are enabled, and we don't want to clobber the true passphrase error.
1280 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1282 // Make sure the data types that depend on the passphrase are started at
1284 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1285 if (data_type_manager_
) {
1286 // Re-enable any encrypted types if necessary.
1287 data_type_manager_
->Configure(types
,
1288 syncer::CONFIGURE_REASON_CRYPTO
);
1294 void ProfileSyncService::OnEncryptedTypesChanged(
1295 syncer::ModelTypeSet encrypted_types
,
1296 bool encrypt_everything
) {
1297 encrypted_types_
= encrypted_types
;
1298 encrypt_everything_
= encrypt_everything
;
1299 DVLOG(1) << "Encrypted types changed to "
1300 << syncer::ModelTypeSetToString(encrypted_types_
)
1301 << " (encrypt everything is set to "
1302 << (encrypt_everything_
? "true" : "false") << ")";
1303 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1305 // If sessions are encrypted, full history sync is not possible, and
1306 // delete directives are unnecessary.
1307 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES
) &&
1308 encrypted_types_
.Has(syncer::SESSIONS
)) {
1309 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES
,
1311 "Delete directives not supported with encryption.");
1315 void ProfileSyncService::OnEncryptionComplete() {
1316 DVLOG(1) << "Encryption complete";
1317 if (encryption_pending_
&& encrypt_everything_
) {
1318 encryption_pending_
= false;
1319 // This is to nudge the integration tests when encryption is
1325 void ProfileSyncService::OnMigrationNeededForTypes(
1326 syncer::ModelTypeSet types
) {
1327 DCHECK(backend_initialized_
);
1328 DCHECK(data_type_manager_
.get());
1330 // Migrator must be valid, because we don't sync until it is created and this
1331 // callback originates from a sync cycle.
1332 migrator_
->MigrateTypes(types
);
1335 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1336 last_actionable_error_
= error
;
1337 DCHECK_NE(last_actionable_error_
.action
,
1338 syncer::UNKNOWN_ACTION
);
1339 switch (error
.action
) {
1340 case syncer::UPGRADE_CLIENT
:
1341 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1342 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1343 case syncer::STOP_AND_RESTART_SYNC
:
1344 // TODO(lipalani) : if setup in progress we want to display these
1345 // actions in the popup. The current experience might not be optimal for
1346 // the user. We just dismiss the dialog.
1347 if (setup_in_progress_
) {
1348 StopSyncingPermanently();
1349 expect_sync_configuration_aborted_
= true;
1351 // Trigger an unrecoverable error to stop syncing.
1352 OnInternalUnrecoverableError(FROM_HERE
,
1353 last_actionable_error_
.error_description
,
1355 ERROR_REASON_ACTIONABLE_ERROR
);
1357 case syncer::DISABLE_SYNC_ON_CLIENT
:
1358 StopSyncingPermanently();
1359 #if !defined(OS_CHROMEOS)
1360 // On desktop Chrome, sign out the user after a dashboard clear.
1361 // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049.
1362 if (!auto_start_enabled_
) // Skip sign out on ChromeOS/Android.
1363 SigninManagerFactory::GetForProfile(profile_
)->SignOut();
1366 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1367 // Sync disabled by domain admin. we should stop syncing until next
1369 sync_disabled_by_admin_
= true;
1370 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD
);
1378 void ProfileSyncService::OnConfigureDone(
1379 const browser_sync::DataTypeManager::ConfigureResult
& result
) {
1380 // We should have cleared our cached passphrase before we get here (in
1381 // OnBackendInitialized()).
1382 DCHECK(cached_passphrase_
.empty());
1384 if (!sync_configure_start_time_
.is_null()) {
1385 if (result
.status
== DataTypeManager::OK
||
1386 result
.status
== DataTypeManager::PARTIAL_SUCCESS
) {
1387 base::Time sync_configure_stop_time
= base::Time::Now();
1388 base::TimeDelta delta
= sync_configure_stop_time
-
1389 sync_configure_start_time_
;
1390 if (is_first_time_sync_configure_
) {
1391 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1393 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1397 sync_configure_start_time_
= base::Time();
1400 // Notify listeners that configuration is done.
1401 content::NotificationService::current()->Notify(
1402 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1403 content::Source
<ProfileSyncService
>(this),
1404 content::NotificationService::NoDetails());
1406 configure_status_
= result
.status
;
1407 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1408 // The possible status values:
1409 // ABORT - Configuration was aborted. This is not an error, if
1410 // initiated by user.
1411 // OK - Everything succeeded.
1412 // PARTIAL_SUCCESS - Some datatypes failed to start.
1413 // Everything else is an UnrecoverableError. So treat it as such.
1415 // First handle the abort case.
1416 if (configure_status_
== DataTypeManager::ABORTED
&&
1417 expect_sync_configuration_aborted_
) {
1418 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1419 expect_sync_configuration_aborted_
= false;
1423 // Handle unrecoverable error.
1424 if (configure_status_
!= DataTypeManager::OK
&&
1425 configure_status_
!= DataTypeManager::PARTIAL_SUCCESS
) {
1426 // Something catastrophic had happened. We should only have one
1427 // error representing it.
1428 DCHECK_EQ(result
.failed_data_types
.size(),
1429 static_cast<unsigned int>(1));
1430 syncer::SyncError error
= result
.failed_data_types
.begin()->second
;
1431 DCHECK(error
.IsSet());
1432 std::string message
=
1433 "Sync configuration failed with status " +
1434 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1435 " during " + syncer::ModelTypeToString(error
.model_type()) +
1436 ": " + error
.message();
1437 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1438 OnInternalUnrecoverableError(error
.location(),
1441 ERROR_REASON_CONFIGURATION_FAILURE
);
1445 // We should never get in a state where we have no encrypted datatypes
1446 // enabled, and yet we still think we require a passphrase for decryption.
1447 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1448 !IsEncryptedDatatypeEnabled()));
1450 // This must be done before we start syncing with the server to avoid
1451 // sending unencrypted data up on a first time sync.
1452 if (encryption_pending_
)
1453 backend_
->EnableEncryptEverything();
1456 if (migrator_
.get() &&
1457 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1458 // Migration in progress. Let the migrator know we just finished
1459 // configuring something. It will be up to the migrator to call
1460 // StartSyncingWithServer() if migration is now finished.
1461 migrator_
->OnConfigureDone(result
);
1463 StartSyncingWithServer();
1467 void ProfileSyncService::OnConfigureRetry() {
1468 // We should have cleared our cached passphrase before we get here (in
1469 // OnBackendInitialized()).
1470 DCHECK(cached_passphrase_
.empty());
1472 OnSyncConfigureRetry();
1475 void ProfileSyncService::OnConfigureStart() {
1476 sync_configure_start_time_
= base::Time::Now();
1480 ProfileSyncService::SyncStatusSummary
1481 ProfileSyncService::QuerySyncStatusSummary() {
1482 if (HasUnrecoverableError()) {
1483 return UNRECOVERABLE_ERROR
;
1484 } else if (!backend_
) {
1486 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1487 return SETUP_INCOMPLETE
;
1488 } else if (backend_
.get() && HasSyncSetupCompleted() &&
1489 data_type_manager_
.get() &&
1490 data_type_manager_
->state() != DataTypeManager::CONFIGURED
) {
1491 return DATATYPES_NOT_INITIALIZED
;
1492 } else if (ShouldPushChanges()) {
1495 return UNKNOWN_ERROR
;
1498 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1499 SyncStatusSummary status
= QuerySyncStatusSummary();
1501 case UNRECOVERABLE_ERROR
:
1502 return "Unrecoverable error detected";
1504 return "Syncing not enabled";
1505 case SETUP_INCOMPLETE
:
1506 return "First time sync setup incomplete";
1507 case DATATYPES_NOT_INITIALIZED
:
1508 return "Datatypes not fully initialized";
1510 return "Sync service initialized";
1512 return "Status unknown: Internal error?";
1516 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1517 if (sync_initialized())
1519 else if (!start_up_time_
.is_null())
1522 return "Not started";
1525 bool ProfileSyncService::QueryDetailedSyncStatus(
1526 SyncBackendHost::Status
* result
) {
1527 if (backend_
.get() && backend_initialized_
) {
1528 *result
= backend_
->GetDetailedStatus();
1531 SyncBackendHost::Status status
;
1532 status
.sync_protocol_error
= last_actionable_error_
;
1538 const AuthError
& ProfileSyncService::GetAuthError() const {
1539 return last_auth_error_
;
1542 bool ProfileSyncService::FirstSetupInProgress() const {
1543 return !HasSyncSetupCompleted() && setup_in_progress_
;
1546 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1547 // This method is a no-op if |setup_in_progress_| remains unchanged.
1548 if (setup_in_progress_
== setup_in_progress
)
1551 setup_in_progress_
= setup_in_progress
;
1552 if (!setup_in_progress
&& sync_initialized())
1553 ReconfigureDatatypeManager();
1557 bool ProfileSyncService::sync_initialized() const {
1558 return backend_initialized_
;
1561 bool ProfileSyncService::waiting_for_auth() const {
1562 return is_auth_in_progress_
;
1565 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1566 return current_experiments_
;
1569 bool ProfileSyncService::HasUnrecoverableError() const {
1570 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1573 bool ProfileSyncService::IsPassphraseRequired() const {
1574 return passphrase_required_reason_
!=
1575 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1578 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1579 // If there is an encrypted datatype enabled and we don't have the proper
1580 // passphrase, we must prompt the user for a passphrase. The only way for the
1581 // user to avoid entering their passphrase is to disable the encrypted types.
1582 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1585 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1586 if (last_synced_time_
.is_null())
1587 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1589 base::TimeDelta last_synced
= base::Time::Now() - last_synced_time_
;
1591 if (last_synced
< base::TimeDelta::FromMinutes(1))
1592 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1594 return ui::TimeFormat::TimeElapsed(last_synced
);
1597 void ProfileSyncService::UpdateSelectedTypesHistogram(
1598 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1599 if (!HasSyncSetupCompleted() ||
1600 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1601 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1604 // Only log the data types that are shown in the sync settings ui.
1605 // Note: the order of these types must match the ordering of
1606 // the respective types in ModelType
1607 const browser_sync::user_selectable_type::UserSelectableSyncType
1608 user_selectable_types
[] = {
1609 browser_sync::user_selectable_type::BOOKMARKS
,
1610 browser_sync::user_selectable_type::PREFERENCES
,
1611 browser_sync::user_selectable_type::PASSWORDS
,
1612 browser_sync::user_selectable_type::AUTOFILL
,
1613 browser_sync::user_selectable_type::THEMES
,
1614 browser_sync::user_selectable_type::TYPED_URLS
,
1615 browser_sync::user_selectable_type::EXTENSIONS
,
1616 browser_sync::user_selectable_type::APPS
,
1617 browser_sync::user_selectable_type::PROXY_TABS
1620 COMPILE_ASSERT(32 == syncer::MODEL_TYPE_COUNT
, UpdateCustomConfigHistogram
);
1622 if (!sync_everything
) {
1623 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1625 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1626 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1628 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1630 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1632 const syncer::ModelType type
= it
.Get();
1633 if (chosen_types
.Has(type
) &&
1634 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1635 // Selected type has changed - log it.
1636 UMA_HISTOGRAM_ENUMERATION(
1638 user_selectable_types
[i
],
1639 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1645 #if defined(OS_CHROMEOS)
1646 void ProfileSyncService::RefreshSpareBootstrapToken(
1647 const std::string
& passphrase
) {
1648 browser_sync::SystemEncryptor encryptor
;
1649 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1650 // The first 2 params (hostname and username) doesn't have any effect here.
1651 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1653 std::string bootstrap_token
;
1654 if (!temp_cryptographer
.AddKey(key_params
)) {
1655 NOTREACHED() << "Failed to add key to cryptographer.";
1657 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1658 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1662 void ProfileSyncService::OnUserChoseDatatypes(
1663 bool sync_everything
,
1664 syncer::ModelTypeSet chosen_types
) {
1665 if (!backend_
.get() && !HasUnrecoverableError()) {
1670 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1671 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1673 failed_data_types_handler_
.Reset();
1674 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES
) &&
1675 encrypted_types_
.Has(syncer::SESSIONS
)) {
1676 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES
,
1678 "Delete directives not supported with encryption.");
1680 ChangePreferredDataTypes(chosen_types
);
1681 AcknowledgeSyncedTypes();
1685 void ProfileSyncService::ChangePreferredDataTypes(
1686 syncer::ModelTypeSet preferred_types
) {
1688 DVLOG(1) << "ChangePreferredDataTypes invoked";
1689 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1690 const syncer::ModelTypeSet registered_preferred_types
=
1691 Intersection(registered_types
, preferred_types
);
1692 sync_prefs_
.SetPreferredDataTypes(registered_types
,
1693 registered_preferred_types
);
1695 // Now reconfigure the DTM.
1696 ReconfigureDatatypeManager();
1699 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1700 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1701 const syncer::ModelTypeSet failed_types
=
1702 failed_data_types_handler_
.GetFailedTypes();
1703 return Difference(preferred_types
, failed_types
);
1706 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1707 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1708 const syncer::ModelTypeSet preferred_types
=
1709 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1710 return preferred_types
;
1713 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1714 syncer::ModelTypeSet registered_types
;
1715 // The data_type_controllers_ are determined by command-line flags; that's
1716 // effectively what controls the values returned here.
1717 for (DataTypeController::TypeMap::const_iterator it
=
1718 data_type_controllers_
.begin();
1719 it
!= data_type_controllers_
.end(); ++it
) {
1720 registered_types
.Put(it
->first
);
1722 return registered_types
;
1725 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1726 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1727 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1728 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1731 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1732 return backend_
->GetPassphraseType();
1735 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1736 return backend_
->GetExplicitPassphraseTime();
1739 bool ProfileSyncService::IsCryptographerReady(
1740 const syncer::BaseTransaction
* trans
) const {
1741 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1744 void ProfileSyncService::ConfigurePriorityDataTypes() {
1745 const syncer::ModelTypeSet priority_types
=
1746 Intersection(GetPreferredDataTypes(), syncer::PriorityUserTypes());
1747 if (!priority_types
.Empty()) {
1748 const syncer::ConfigureReason reason
= HasSyncSetupCompleted() ?
1749 syncer::CONFIGURE_REASON_RECONFIGURATION
:
1750 syncer::CONFIGURE_REASON_NEW_CLIENT
;
1751 data_type_manager_
->Configure(priority_types
, reason
);
1755 void ProfileSyncService::ConfigureDataTypeManager() {
1756 // Don't configure datatypes if the setup UI is still on the screen - this
1757 // is to help multi-screen setting UIs (like iOS) where they don't want to
1758 // start syncing data until the user is done configuring encryption options,
1759 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1760 // SetSetupInProgress(false).
1761 if (setup_in_progress_
)
1764 bool restart
= false;
1765 if (!data_type_manager_
) {
1767 data_type_manager_
.reset(
1768 factory_
->CreateDataTypeManager(debug_info_listener_
,
1769 &data_type_controllers_
,
1773 &failed_data_types_handler_
));
1775 // We create the migrator at the same time.
1777 new browser_sync::BackendMigrator(
1778 profile_
->GetDebugName(), GetUserShare(),
1779 this, data_type_manager_
.get(),
1780 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1781 base::Unretained(this))));
1784 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1785 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1786 if (!HasSyncSetupCompleted()) {
1787 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1788 } else if (restart
) {
1789 // Datatype downloads on restart are generally due to newly supported
1790 // datatypes (although it's also possible we're picking up where a failed
1791 // previous configuration left off).
1792 // TODO(sync): consider detecting configuration recovery and setting
1793 // the reason here appropriately.
1794 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1796 // The user initiated a reconfiguration (either to add or remove types).
1797 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1800 data_type_manager_
->Configure(types
, reason
);
1803 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1804 if (backend_
.get() && backend_initialized_
) {
1805 return backend_
->GetUserShare();
1811 syncer::sessions::SyncSessionSnapshot
1812 ProfileSyncService::GetLastSessionSnapshot() const {
1813 if (backend_
.get() && backend_initialized_
) {
1814 return backend_
->GetLastSessionSnapshot();
1817 return syncer::sessions::SyncSessionSnapshot();
1820 bool ProfileSyncService::HasUnsyncedItems() const {
1821 if (backend_
.get() && backend_initialized_
) {
1822 return backend_
->HasUnsyncedItems();
1828 browser_sync::BackendMigrator
*
1829 ProfileSyncService::GetBackendMigratorForTest() {
1830 return migrator_
.get();
1833 void ProfileSyncService::GetModelSafeRoutingInfo(
1834 syncer::ModelSafeRoutingInfo
* out
) const {
1835 if (backend_
.get() && backend_initialized_
) {
1836 backend_
->GetModelSafeRoutingInfo(out
);
1842 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
1843 scoped_ptr
<base::ListValue
> result(new base::ListValue());
1845 if (!backend_
.get() || !backend_initialized_
) {
1846 return result
.release();
1849 FailedDataTypesHandler::TypeErrorMap error_map
=
1850 failed_data_types_handler_
.GetAllErrors();
1852 ModelTypeSet active_types
;
1853 ModelTypeSet passive_types
;
1854 ModelSafeRoutingInfo routing_info
;
1855 backend_
->GetModelSafeRoutingInfo(&routing_info
);
1856 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
1857 it
!= routing_info
.end(); ++it
) {
1858 if (it
->second
== syncer::GROUP_PASSIVE
) {
1859 passive_types
.Put(it
->first
);
1861 active_types
.Put(it
->first
);
1865 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
1866 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
1867 ModelTypeSet registered
= GetRegisteredDataTypes();
1868 scoped_ptr
<base::DictionaryValue
> type_status_header(
1869 new base::DictionaryValue());
1871 type_status_header
->SetString("name", "Model Type");
1872 type_status_header
->SetString("status", "header");
1873 type_status_header
->SetString("value", "Group Type");
1874 type_status_header
->SetString("num_entries", "Total Entries");
1875 type_status_header
->SetString("num_live", "Live Entries");
1876 result
->Append(type_status_header
.release());
1878 scoped_ptr
<base::DictionaryValue
> type_status
;
1879 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
1880 ModelType type
= it
.Get();
1882 type_status
.reset(new base::DictionaryValue());
1883 type_status
->SetString("name", ModelTypeToString(type
));
1885 if (error_map
.find(type
) != error_map
.end()) {
1886 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
1887 DCHECK(error
.IsSet());
1888 std::string error_text
= "Error: " + error
.location().ToString() +
1889 ", " + error
.message();
1890 type_status
->SetString("status", "error");
1891 type_status
->SetString("value", error_text
);
1892 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
1893 type_status
->SetString("status", "warning");
1894 type_status
->SetString("value", "Passive, Throttled");
1895 } else if (passive_types
.Has(type
)) {
1896 type_status
->SetString("status", "warning");
1897 type_status
->SetString("value", "Passive");
1898 } else if (throttled_types
.Has(type
)) {
1899 type_status
->SetString("status", "warning");
1900 type_status
->SetString("value", "Throttled");
1901 } else if (active_types
.Has(type
)) {
1902 type_status
->SetString("status", "ok");
1903 type_status
->SetString("value", "Active: " +
1904 ModelSafeGroupToString(routing_info
[type
]));
1906 type_status
->SetString("status", "warning");
1907 type_status
->SetString("value", "Disabled by User");
1910 int live_count
= detailed_status
.num_entries_by_type
[type
] -
1911 detailed_status
.num_to_delete_entries_by_type
[type
];
1912 type_status
->SetInteger("num_entries",
1913 detailed_status
.num_entries_by_type
[type
]);
1914 type_status
->SetInteger("num_live", live_count
);
1916 result
->Append(type_status
.release());
1918 return result
.release();
1921 void ProfileSyncService::ActivateDataType(
1922 syncer::ModelType type
, syncer::ModelSafeGroup group
,
1923 ChangeProcessor
* change_processor
) {
1928 DCHECK(backend_initialized_
);
1929 backend_
->ActivateDataType(type
, group
, change_processor
);
1932 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
1935 backend_
->DeactivateDataType(type
);
1938 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
1939 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
1940 // If the backend isn't running yet, OnBackendInitialized() will call this
1941 // method again after the backend starts up.
1942 if (cached_passphrase_
.empty() || !sync_initialized())
1945 // Backend is up and running, so we can consume the cached passphrase.
1946 std::string passphrase
= cached_passphrase_
;
1947 cached_passphrase_
.clear();
1949 // If we need a passphrase to decrypt data, try the cached passphrase.
1950 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
1951 if (SetDecryptionPassphrase(passphrase
)) {
1952 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
1957 // If we get here, we don't have pending keys (or at least, the passphrase
1958 // doesn't decrypt them) - just try to re-encrypt using the encryption
1960 if (!IsUsingSecondaryPassphrase())
1961 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
1964 void ProfileSyncService::RequestAccessToken() {
1965 // Only one active request at a time.
1966 if (access_token_request_
!= NULL
)
1968 request_access_token_retry_timer_
.Stop();
1969 OAuth2TokenService::ScopeSet oauth2_scopes
;
1970 if (profile_
->IsManaged()) {
1971 oauth2_scopes
.insert(GaiaConstants::kChromeSyncManagedOAuth2Scope
);
1973 oauth2_scopes
.insert(GaiaConstants::kChromeSyncOAuth2Scope
);
1976 // Invalidate previous token, otherwise token service will return the same
1978 const std::string
& account_id
= signin_
->GetAccountIdToUse();
1979 if (!access_token_
.empty()) {
1980 oauth2_token_service_
->InvalidateToken(
1981 account_id
, oauth2_scopes
, access_token_
);
1984 access_token_
.clear();
1986 token_request_time_
= base::Time::Now();
1987 token_receive_time_
= base::Time();
1988 next_token_request_time_
= base::Time();
1989 access_token_request_
=
1990 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
1993 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
1994 PassphraseType type
) {
1995 // This should only be called when the backend has been initialized.
1996 DCHECK(sync_initialized());
1997 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
1998 "Data is already encrypted using an explicit passphrase";
1999 DCHECK(!(type
== EXPLICIT
&&
2000 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2001 "Can not set explicit passphrase when decryption is needed.";
2003 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2004 << " passphrase for encryption.";
2005 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2006 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2007 // keys. Hence, as long as we're not trying to do an invalid passphrase
2008 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2009 // will succeed. If for some reason a new encryption key arrives via
2010 // sync later, the SBH will trigger another OnPassphraseRequired().
2011 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2014 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2017 bool ProfileSyncService::SetDecryptionPassphrase(
2018 const std::string
& passphrase
) {
2019 if (IsPassphraseRequired()) {
2020 DVLOG(1) << "Setting passphrase for decryption.";
2021 return backend_
->SetDecryptionPassphrase(passphrase
);
2023 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2024 "IsPassphraseRequired() is false.";
2029 void ProfileSyncService::EnableEncryptEverything() {
2030 // Tests override sync_initialized() to always return true, so we
2031 // must check that instead of |backend_initialized_|.
2032 // TODO(akalin): Fix the above. :/
2033 DCHECK(sync_initialized());
2034 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2035 // problems around cancelling encryption in the background (crbug.com/119649).
2036 if (!encrypt_everything_
)
2037 encryption_pending_
= true;
2040 bool ProfileSyncService::encryption_pending() const {
2041 // We may be called during the setup process before we're
2042 // initialized (via IsEncryptedDatatypeEnabled and
2043 // IsPassphraseRequiredForDecryption).
2044 return encryption_pending_
;
2047 bool ProfileSyncService::EncryptEverythingEnabled() const {
2048 DCHECK(backend_initialized_
);
2049 return encrypt_everything_
|| encryption_pending_
;
2052 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2053 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2054 // We may be called during the setup process before we're
2055 // initialized. In this case, we default to the sensitive types.
2056 return encrypted_types_
;
2059 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2061 if (is_sync_managed
) {
2064 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2069 void ProfileSyncService::Observe(int type
,
2070 const content::NotificationSource
& source
,
2071 const content::NotificationDetails
& details
) {
2073 case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
: {
2074 const GoogleServiceSigninSuccessDetails
* successful
=
2075 content::Details
<const GoogleServiceSigninSuccessDetails
>(
2077 if (!sync_prefs_
.IsStartSuppressed() &&
2078 !successful
->password
.empty()) {
2079 cached_passphrase_
= successful
->password
;
2080 // Try to consume the passphrase we just cached. If the sync backend
2081 // is not running yet, the passphrase will remain cached until the
2082 // backend starts up.
2083 ConsumeCachedPassphraseIfPossible();
2085 #if defined(OS_CHROMEOS)
2086 RefreshSpareBootstrapToken(successful
->password
);
2088 if (!sync_initialized() ||
2089 GetAuthError().state() != AuthError::NONE
) {
2090 // Track the fact that we're still waiting for auth to complete.
2091 is_auth_in_progress_
= true;
2095 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT
:
2096 sync_disabled_by_admin_
= false;
2105 void ProfileSyncService::AddObserver(
2106 ProfileSyncServiceBase::Observer
* observer
) {
2107 observers_
.AddObserver(observer
);
2110 void ProfileSyncService::RemoveObserver(
2111 ProfileSyncServiceBase::Observer
* observer
) {
2112 observers_
.RemoveObserver(observer
);
2115 bool ProfileSyncService::HasObserver(
2116 ProfileSyncServiceBase::Observer
* observer
) const {
2117 return observers_
.HasObserver(observer
);
2120 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2121 return sync_js_controller_
.AsWeakPtr();
2124 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2125 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2129 bool ProfileSyncService::IsSyncEnabled() {
2130 // We have switches::kEnableSync just in case we need to change back to
2131 // sync-disabled-by-default on a platform.
2132 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync
);
2135 bool ProfileSyncService::IsManaged() const {
2136 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2139 bool ProfileSyncService::ShouldPushChanges() {
2140 // True only after all bootstrapping has succeeded: the sync backend
2141 // is initialized, all enabled data types are consistent with one
2142 // another, and no unrecoverable error has transpired.
2143 if (HasUnrecoverableError())
2146 if (!data_type_manager_
)
2149 return data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
2152 void ProfileSyncService::StopAndSuppress() {
2153 sync_prefs_
.SetStartSuppressed(true);
2155 backend_
->UnregisterInvalidationIds();
2157 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD
);
2160 bool ProfileSyncService::IsStartSuppressed() const {
2161 return sync_prefs_
.IsStartSuppressed();
2164 SigninManagerBase
* ProfileSyncService::signin() const {
2165 return signin_
->GetOriginal();
2168 void ProfileSyncService::UnsuppressAndStart() {
2170 sync_prefs_
.SetStartSuppressed(false);
2171 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess
2172 // is never called for some clients.
2173 if (signin_
.get() &&
2174 signin_
->GetOriginal()->GetAuthenticatedUsername().empty()) {
2175 signin_
->GetOriginal()->SetAuthenticatedUsername(
2176 sync_prefs_
.GetGoogleServicesUsername());
2181 void ProfileSyncService::AcknowledgeSyncedTypes() {
2182 sync_prefs_
.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2185 void ProfileSyncService::ReconfigureDatatypeManager() {
2186 // If we haven't initialized yet, don't configure the DTM as it could cause
2187 // association to start before a Directory has even been created.
2188 if (backend_initialized_
) {
2189 DCHECK(backend_
.get());
2190 ConfigureDataTypeManager();
2191 } else if (HasUnrecoverableError()) {
2192 // There is nothing more to configure. So inform the listeners,
2195 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2196 << "Unrecoverable error.";
2198 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2203 const FailedDataTypesHandler
& ProfileSyncService::failed_data_types_handler()
2205 return failed_data_types_handler_
;
2208 void ProfileSyncService::OnInternalUnrecoverableError(
2209 const tracked_objects::Location
& from_here
,
2210 const std::string
& message
,
2211 bool delete_sync_database
,
2212 UnrecoverableErrorReason reason
) {
2213 DCHECK(!HasUnrecoverableError());
2214 unrecoverable_error_reason_
= reason
;
2215 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2218 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2219 return request_access_token_retry_timer_
.IsRunning();
2222 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2223 return access_token_
;
2226 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2227 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2230 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2231 return sessions_sync_manager_
.get();
2234 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2235 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED
),
2236 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2237 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2239 ProfileSyncService::SyncTokenStatus
2240 ProfileSyncService::GetSyncTokenStatus() const {
2241 SyncTokenStatus status
;
2242 status
.connection_status_update_time
= connection_status_update_time_
;
2243 status
.connection_status
= connection_status_
;
2244 status
.token_request_time
= token_request_time_
;
2245 status
.token_receive_time
= token_receive_time_
;
2246 status
.last_get_token_error
= last_get_token_error_
;
2247 if (request_access_token_retry_timer_
.IsRunning())
2248 status
.next_token_request_time
= next_token_request_time_
;
2252 void ProfileSyncService::OverrideNetworkResourcesForTest(
2253 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2254 network_resources_
= network_resources
.Pass();