Fix build break
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blobb3d6c949226f287a9032e9be27f8924b492f4862
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"
7 #include <cstddef>
8 #include <map>
9 #include <set>
10 #include <utility>
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.h"
20 #include "base/metrics/histogram.h"
21 #include "base/string16.h"
22 #include "base/stringprintf.h"
23 #include "base/threading/thread_restrictions.h"
24 #include "build/build_config.h"
25 #include "chrome/browser/about_flags.h"
26 #include "chrome/browser/browser_process.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/signin_manager.h"
32 #include "chrome/browser/signin/signin_manager_factory.h"
33 #include "chrome/browser/signin/token_service.h"
34 #include "chrome/browser/signin/token_service_factory.h"
35 #include "chrome/browser/sync/backend_migrator.h"
36 #include "chrome/browser/sync/glue/change_processor.h"
37 #include "chrome/browser/sync/glue/chrome_encryptor.h"
38 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
39 #include "chrome/browser/sync/glue/data_type_controller.h"
40 #include "chrome/browser/sync/glue/device_info.h"
41 #include "chrome/browser/sync/glue/session_data_type_controller.h"
42 #include "chrome/browser/sync/glue/session_model_associator.h"
43 #include "chrome/browser/sync/glue/synced_device_tracker.h"
44 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
45 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
46 #include "chrome/browser/sync/sync_global_error.h"
47 #include "chrome/browser/sync/user_selectable_sync_type.h"
48 #include "chrome/browser/ui/browser.h"
49 #include "chrome/browser/ui/browser_list.h"
50 #include "chrome/browser/ui/browser_window.h"
51 #include "chrome/browser/ui/global_error/global_error_service.h"
52 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
53 #include "chrome/common/chrome_notification_types.h"
54 #include "chrome/common/chrome_switches.h"
55 #include "chrome/common/chrome_version_info.h"
56 #include "chrome/common/pref_names.h"
57 #include "chrome/common/time_format.h"
58 #include "chrome/common/url_constants.h"
59 #include "components/user_prefs/pref_registry_syncable.h"
60 #include "content/public/browser/notification_details.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/notification_source.h"
63 #include "google_apis/gaia/gaia_constants.h"
64 #include "grit/generated_resources.h"
65 #include "net/cookies/cookie_monster.h"
66 #include "sync/api/sync_error.h"
67 #include "sync/internal_api/public/configure_reason.h"
68 #include "sync/internal_api/public/sync_encryption_handler.h"
69 #include "sync/internal_api/public/util/experiments.h"
70 #include "sync/internal_api/public/util/sync_string_conversions.h"
71 #include "sync/js/js_arg_list.h"
72 #include "sync/js/js_event_details.h"
73 #include "sync/notifier/invalidator_registrar.h"
74 #include "sync/notifier/invalidator_state.h"
75 #include "sync/util/cryptographer.h"
76 #include "ui/base/l10n/l10n_util.h"
78 #if defined(OS_ANDROID)
79 #include "sync/internal_api/public/read_transaction.h"
80 #endif
82 using browser_sync::ChangeProcessor;
83 using browser_sync::DataTypeController;
84 using browser_sync::DataTypeManager;
85 using browser_sync::SyncBackendHost;
86 using syncer::ModelType;
87 using syncer::ModelTypeSet;
88 using syncer::JsBackend;
89 using syncer::JsController;
90 using syncer::JsEventDetails;
91 using syncer::JsEventHandler;
92 using syncer::ModelSafeRoutingInfo;
93 using syncer::SyncCredentials;
94 using syncer::SyncProtocolError;
95 using syncer::WeakHandle;
97 typedef GoogleServiceAuthError AuthError;
99 const char* ProfileSyncService::kSyncServerUrl =
100 "https://clients4.google.com/chrome-sync";
102 const char* ProfileSyncService::kDevServerUrl =
103 "https://clients4.google.com/chrome-sync/dev";
105 static const int kSyncClearDataTimeoutInSeconds = 60; // 1 minute.
107 static const char* kRelevantTokenServices[] = {
108 GaiaConstants::kSyncService
110 static const int kRelevantTokenServicesCount =
111 arraysize(kRelevantTokenServices);
113 static const char* kSyncUnrecoverableErrorHistogram =
114 "Sync.UnrecoverableErrors";
116 // Helper to check if the given token service is relevant for sync.
117 static bool IsTokenServiceRelevant(const std::string& service) {
118 for (int i = 0; i < kRelevantTokenServicesCount; ++i) {
119 if (service == kRelevantTokenServices[i])
120 return true;
122 return false;
125 bool ShouldShowActionOnUI(
126 const syncer::SyncProtocolError& error) {
127 return (error.action != syncer::UNKNOWN_ACTION &&
128 error.action != syncer::DISABLE_SYNC_ON_CLIENT);
131 ProfileSyncService::ProfileSyncService(ProfileSyncComponentsFactory* factory,
132 Profile* profile,
133 SigninManager* signin_manager,
134 StartBehavior start_behavior)
135 : last_auth_error_(AuthError::AuthErrorNone()),
136 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
137 factory_(factory),
138 profile_(profile),
139 // |profile| may be NULL in unit tests.
140 sync_prefs_(profile_ ? profile_->GetPrefs() : NULL),
141 invalidator_storage_(profile_ ? profile_->GetPrefs(): NULL),
142 sync_service_url_(kDevServerUrl),
143 is_first_time_sync_configure_(false),
144 backend_initialized_(false),
145 is_auth_in_progress_(false),
146 signin_(signin_manager),
147 unrecoverable_error_reason_(ERROR_REASON_UNSET),
148 weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
149 expect_sync_configuration_aborted_(false),
150 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
151 encrypt_everything_(false),
152 encryption_pending_(false),
153 auto_start_enabled_(start_behavior == AUTO_START),
154 failed_datatypes_handler_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
155 configure_status_(DataTypeManager::UNKNOWN),
156 setup_in_progress_(false),
157 invalidator_state_(syncer::DEFAULT_INVALIDATION_ERROR) {
158 // By default, dev, canary, and unbranded Chromium users will go to the
159 // development servers. Development servers have more features than standard
160 // sync servers. Users with officially-branded Chrome stable and beta builds
161 // will go to the standard sync servers.
163 // GetChannel hits the registry on Windows. See http://crbug.com/70380.
164 base::ThreadRestrictions::ScopedAllowIO allow_io;
165 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
166 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
167 channel == chrome::VersionInfo::CHANNEL_BETA) {
168 sync_service_url_ = GURL(kSyncServerUrl);
170 if (signin_)
171 signin_->signin_global_error()->AddProvider(this);
174 ProfileSyncService::~ProfileSyncService() {
175 sync_prefs_.RemoveSyncPrefObserver(this);
176 // Shutdown() should have been called before destruction.
177 CHECK(!backend_initialized_);
180 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
181 // Exit if sync is disabled.
182 if (IsManaged() || sync_prefs_.IsStartSuppressed())
183 return false;
185 // Sync is logged in if there is a non-empty authenticated username.
186 return !signin_->GetAuthenticatedUsername().empty();
189 bool ProfileSyncService::IsSyncTokenAvailable() {
190 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
191 if (!token_service)
192 return false;
193 return token_service->HasTokenForService(GaiaConstants::kSyncService);
195 #if defined(OS_ANDROID)
196 bool ProfileSyncService::ShouldEnablePasswordSyncForAndroid() const {
197 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
198 const syncer::ModelTypeSet preferred_types =
199 sync_prefs_.GetPreferredDataTypes(registered_types);
200 if (!preferred_types.Has(syncer::PASSWORDS))
201 return false;
202 // If backend has not completed initializing we cannot check if the
203 // cryptographer is ready.
204 if (!sync_initialized())
205 return false;
206 // On Android we do not want to prompt user to enter a passphrase. If
207 // passwords cannot be decrypted we just disable them.
208 syncer::ReadTransaction trans(FROM_HERE, GetUserShare());
209 return IsCryptographerReady(&trans);
211 #endif
213 void ProfileSyncService::Initialize() {
214 DCHECK(!invalidator_registrar_.get());
215 invalidator_registrar_.reset(new syncer::InvalidatorRegistrar());
217 InitSettings();
219 // We clear this here (vs Shutdown) because we want to remember that an error
220 // happened on shutdown so we can display details (message, location) about it
221 // in about:sync.
222 ClearStaleErrors();
224 sync_prefs_.AddSyncPrefObserver(this);
226 // For now, the only thing we can do through policy is to turn sync off.
227 if (IsManaged()) {
228 DisableForUser();
229 return;
232 RegisterAuthNotifications();
234 if (!HasSyncSetupCompleted() || signin_->GetAuthenticatedUsername().empty()) {
235 // Clean up in case of previous crash / setup abort / signout.
236 DisableForUser();
239 TrySyncDatatypePrefRecovery();
241 TryStart();
244 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
245 DCHECK(!sync_initialized());
246 if (!HasSyncSetupCompleted())
247 return;
249 // There was a bug where OnUserChoseDatatypes was not properly called on
250 // configuration (see crbug.com/154940). We detect this by checking whether
251 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
252 // completed, it means sync was not properly configured, so we manually
253 // set kSyncKeepEverythingSynced.
254 PrefService* const pref_service = profile_->GetPrefs();
255 if (!pref_service)
256 return;
257 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
258 if (sync_prefs_.GetPreferredDataTypes(registered_types).Size() > 1)
259 return;
261 const PrefService::Preference* keep_everything_synced =
262 pref_service->FindPreference(prefs::kSyncKeepEverythingSynced);
263 // This will be false if the preference was properly set or if it's controlled
264 // by policy.
265 if (!keep_everything_synced->IsDefaultValue())
266 return;
268 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
269 // types now, before we configure.
270 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
271 sync_prefs_.SetKeepEverythingSynced(true);
272 sync_prefs_.SetPreferredDataTypes(registered_types,
273 registered_types);
276 void ProfileSyncService::TryStart() {
277 if (!IsSyncEnabledAndLoggedIn())
278 return;
279 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
280 if (!token_service)
281 return;
282 // Don't start the backend if the token service hasn't finished loading tokens
283 // yet. Note if the backend is started before the sync token has been loaded,
284 // GetCredentials() will return bogus credentials. On auto_start platforms
285 // (like ChromeOS) we don't start sync until tokens are loaded, because the
286 // user can be "signed in" on those platforms long before the tokens get
287 // loaded, and we don't want to generate spurious auth errors.
288 if (!IsSyncTokenAvailable() &&
289 !(!auto_start_enabled_ && token_service->TokensLoadedFromDB())) {
290 return;
293 // If sync setup has completed we always start the backend. If the user is in
294 // the process of setting up now, we should start the backend to download
295 // account control state / encryption information). If autostart is enabled,
296 // but we haven't completed sync setup, we try to start sync anyway, since
297 // it's possible we crashed/shutdown after logging in but before the backend
298 // finished initializing the last time.
300 // However, the only time we actually need to start sync _immediately_ is if
301 // we haven't completed sync setup and the user is in the process of setting
302 // up - either they just signed in (for the first time) on an auto-start
303 // platform or they explicitly kicked off sync setup, and e.g we need to
304 // fetch account details like encryption state to populate UI. Otherwise,
305 // for performance reasons and maximizing parallelism at chrome startup, we
306 // defer the heavy lifting for sync init until things have calmed down.
307 if (HasSyncSetupCompleted()) {
308 StartUp(STARTUP_BACKEND_DEFERRED);
309 } else if (setup_in_progress_ || auto_start_enabled_) {
310 // We haven't completed sync setup. Start immediately if the user explicitly
311 // kicked this off or we're supposed to automatically start syncing.
312 StartUp(STARTUP_IMMEDIATE);
316 void ProfileSyncService::StartSyncingWithServer() {
317 if (backend_.get())
318 backend_->StartSyncingWithServer();
321 void ProfileSyncService::RegisterAuthNotifications() {
322 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
323 registrar_.Add(this,
324 chrome::NOTIFICATION_TOKEN_AVAILABLE,
325 content::Source<TokenService>(token_service));
326 registrar_.Add(this,
327 chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
328 content::Source<TokenService>(token_service));
329 registrar_.Add(this,
330 chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
331 content::Source<TokenService>(token_service));
332 registrar_.Add(this,
333 chrome::NOTIFICATION_TOKENS_CLEARED,
334 content::Source<TokenService>(token_service));
335 registrar_.Add(this,
336 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
337 content::Source<Profile>(profile_));
338 registrar_.Add(this,
339 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT,
340 content::Source<Profile>(profile_));
343 void ProfileSyncService::RegisterDataTypeController(
344 DataTypeController* data_type_controller) {
345 DCHECK_EQ(data_type_controllers_.count(data_type_controller->type()), 0U);
346 data_type_controllers_[data_type_controller->type()] =
347 data_type_controller;
350 browser_sync::SessionModelAssociator*
351 ProfileSyncService::GetSessionModelAssociator() {
352 if (data_type_controllers_.find(syncer::SESSIONS) ==
353 data_type_controllers_.end() ||
354 data_type_controllers_.find(syncer::SESSIONS)->second->state() !=
355 DataTypeController::RUNNING) {
356 return NULL;
358 return static_cast<browser_sync::SessionDataTypeController*>(
359 data_type_controllers_.find(
360 syncer::SESSIONS)->second.get())->GetModelAssociator();
363 scoped_ptr<browser_sync::DeviceInfo>
364 ProfileSyncService::GetLocalDeviceInfo() const {
365 DCHECK(sync_initialized());
366 browser_sync::SyncedDeviceTracker* device_tracker =
367 backend_->GetSyncedDeviceTracker();
368 if (device_tracker)
369 return device_tracker->ReadLocalDeviceInfo();
370 else
371 return scoped_ptr<browser_sync::DeviceInfo>();
374 scoped_ptr<browser_sync::DeviceInfo>
375 ProfileSyncService::GetDeviceInfo(const std::string& client_id) const {
376 DCHECK(sync_initialized());
377 browser_sync::SyncedDeviceTracker* device_tracker =
378 backend_->GetSyncedDeviceTracker();
379 if (device_tracker)
380 return device_tracker->ReadDeviceInfo(client_id);
381 else
382 return scoped_ptr<browser_sync::DeviceInfo>();
385 void ProfileSyncService::GetDataTypeControllerStates(
386 browser_sync::DataTypeController::StateMap* state_map) const {
387 for (browser_sync::DataTypeController::TypeMap::const_iterator iter =
388 data_type_controllers_.begin(); iter != data_type_controllers_.end();
389 ++iter)
390 (*state_map)[iter->first] = iter->second.get()->state();
393 void ProfileSyncService::InitSettings() {
394 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
396 // Override the sync server URL from the command-line, if sync server
397 // command-line argument exists.
398 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
399 std::string value(command_line.GetSwitchValueASCII(
400 switches::kSyncServiceURL));
401 if (!value.empty()) {
402 GURL custom_sync_url(value);
403 if (custom_sync_url.is_valid()) {
404 sync_service_url_ = custom_sync_url;
405 } else {
406 LOG(WARNING) << "The following sync URL specified at the command-line "
407 << "is invalid: " << value;
413 SyncCredentials ProfileSyncService::GetCredentials() {
414 SyncCredentials credentials;
415 credentials.email = signin_->GetAuthenticatedUsername();
416 DCHECK(!credentials.email.empty());
417 TokenService* service = TokenServiceFactory::GetForProfile(profile_);
418 if (service->HasTokenForService(GaiaConstants::kSyncService)) {
419 credentials.sync_token = service->GetTokenForService(
420 GaiaConstants::kSyncService);
421 UMA_HISTOGRAM_BOOLEAN("Sync.CredentialsLost", false);
422 } else {
423 // We've lost our sync credentials (crbug.com/121755), so just make up some
424 // invalid credentials so the backend will generate an auth error.
425 UMA_HISTOGRAM_BOOLEAN("Sync.CredentialsLost", true);
426 credentials.sync_token = "credentials_lost";
428 return credentials;
431 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
432 if (!backend_.get()) {
433 NOTREACHED();
434 return;
437 SyncCredentials credentials = GetCredentials();
439 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
440 profile_->GetRequestContext());
442 if (delete_stale_data)
443 ClearStaleErrors();
445 backend_unrecoverable_error_handler_.reset(
446 new browser_sync::BackendUnrecoverableErrorHandler(
447 MakeWeakHandle(weak_factory_.GetWeakPtr())));
449 backend_->Initialize(
450 this,
451 MakeWeakHandle(sync_js_controller_.AsWeakPtr()),
452 sync_service_url_,
453 credentials,
454 delete_stale_data,
455 &sync_manager_factory_,
456 backend_unrecoverable_error_handler_.get(),
457 &browser_sync::ChromeReportUnrecoverableError);
460 void ProfileSyncService::CreateBackend() {
461 backend_.reset(
462 new SyncBackendHost(profile_->GetDebugName(),
463 profile_, sync_prefs_.AsWeakPtr(),
464 invalidator_storage_.AsWeakPtr()));
467 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
468 if (encryption_pending())
469 return true;
470 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
471 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
472 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
473 return !Intersection(preferred_types, encrypted_types).Empty();
476 void ProfileSyncService::OnSyncConfigureDone(
477 DataTypeManager::ConfigureResult result) {
478 if (failed_datatypes_handler_.UpdateFailedDatatypes(result.failed_data_types,
479 FailedDatatypesHandler::STARTUP)) {
480 ReconfigureDatatypeManager();
484 void ProfileSyncService::OnSyncConfigureRetry() {
485 // Note: in order to handle auth failures that arise before the backend is
486 // initialized (e.g. from invalidation notifier, or downloading new control
487 // types), we have to gracefully handle configuration retries at all times.
488 // At this point an auth error badge should be shown, which once resolved
489 // will trigger a new sync cycle.
490 NotifyObservers();
493 void ProfileSyncService::StartUp(StartUpDeferredOption deferred_option) {
494 // Don't start up multiple times.
495 if (backend_.get()) {
496 DVLOG(1) << "Skipping bringing up backend host.";
497 return;
500 DCHECK(IsSyncEnabledAndLoggedIn());
502 last_synced_time_ = sync_prefs_.GetLastSyncedTime();
504 DCHECK(start_up_time_.is_null());
505 start_up_time_ = base::Time::Now();
507 #if defined(OS_CHROMEOS)
508 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
509 if (bootstrap_token.empty()) {
510 sync_prefs_.SetEncryptionBootstrapToken(
511 sync_prefs_.GetSpareBootstrapToken());
513 #endif
515 if (!sync_global_error_.get()) {
516 #if !defined(OS_ANDROID)
517 sync_global_error_.reset(new SyncGlobalError(this, signin()));
518 #endif
519 GlobalErrorServiceFactory::GetForProfile(profile_)->AddGlobalError(
520 sync_global_error_.get());
521 AddObserver(sync_global_error_.get());
524 if (deferred_option == STARTUP_BACKEND_DEFERRED &&
525 CommandLine::ForCurrentProcess()->
526 HasSwitch(switches::kSyncEnableDeferredStartup)) {
527 return;
530 StartUpSlowBackendComponents(STARTUP_IMMEDIATE);
533 void ProfileSyncService::StartUpSlowBackendComponents(
534 StartUpDeferredOption deferred_option) {
535 // Don't start up multiple times.
536 if (backend_.get()) {
537 DVLOG(1) << "Skipping bringing up backend host.";
538 return;
541 DCHECK(!start_up_time_.is_null());
542 if (deferred_option == STARTUP_BACKEND_DEFERRED) {
543 base::TimeDelta time_deferred = base::Time::Now() - start_up_time_;
544 UMA_HISTOGRAM_TIMES("Sync.Startup.TimeDeferred", time_deferred);
547 DCHECK(IsSyncEnabledAndLoggedIn());
548 CreateBackend();
550 // Initialize the backend. Every time we start up a new SyncBackendHost,
551 // we'll want to start from a fresh SyncDB, so delete any old one that might
552 // be there.
553 InitializeBackend(!HasSyncSetupCompleted());
555 // |backend_| may end up being NULL here in tests (in synchronous
556 // initialization mode).
558 // TODO(akalin): Fix this horribly non-intuitive behavior (see
559 // http://crbug.com/140354).
560 if (backend_.get()) {
561 backend_->UpdateRegisteredInvalidationIds(
562 invalidator_registrar_->GetAllRegisteredIds());
563 for (AckHandleReplayQueue::const_iterator it = ack_replay_queue_.begin();
564 it != ack_replay_queue_.end(); ++it) {
565 backend_->AcknowledgeInvalidation(it->first, it->second);
567 ack_replay_queue_.clear();
571 void ProfileSyncService::RegisterInvalidationHandler(
572 syncer::InvalidationHandler* handler) {
573 invalidator_registrar_->RegisterHandler(handler);
576 void ProfileSyncService::UpdateRegisteredInvalidationIds(
577 syncer::InvalidationHandler* handler,
578 const syncer::ObjectIdSet& ids) {
579 invalidator_registrar_->UpdateRegisteredIds(handler, ids);
581 // If |backend_| is NULL, its registered IDs will be updated when
582 // it's created and initialized.
583 if (backend_.get()) {
584 backend_->UpdateRegisteredInvalidationIds(
585 invalidator_registrar_->GetAllRegisteredIds());
589 void ProfileSyncService::UnregisterInvalidationHandler(
590 syncer::InvalidationHandler* handler) {
591 invalidator_registrar_->UnregisterHandler(handler);
594 void ProfileSyncService::AcknowledgeInvalidation(
595 const invalidation::ObjectId& id,
596 const syncer::AckHandle& ack_handle) {
597 if (backend_.get()) {
598 backend_->AcknowledgeInvalidation(id, ack_handle);
599 } else {
600 // If |backend_| is NULL, save the acknowledgements to replay when
601 // it's created and initialized.
602 ack_replay_queue_.push_back(std::make_pair(id, ack_handle));
606 syncer::InvalidatorState ProfileSyncService::GetInvalidatorState() const {
607 return invalidator_registrar_->GetInvalidatorState();
610 void ProfileSyncService::EmitInvalidationForTest(
611 const invalidation::ObjectId& id,
612 const std::string& payload) {
613 syncer::ObjectIdSet notify_ids;
614 notify_ids.insert(id);
616 const syncer::ObjectIdInvalidationMap& invalidation_map =
617 ObjectIdSetToInvalidationMap(notify_ids, payload);
618 OnIncomingInvalidation(invalidation_map);
621 void ProfileSyncService::Shutdown() {
622 DCHECK(invalidator_registrar_.get());
623 // Reset |invalidator_registrar_| first so that ShutdownImpl cannot
624 // use it.
625 invalidator_registrar_.reset();
627 if (signin_)
628 signin_->signin_global_error()->RemoveProvider(this);
630 ShutdownImpl(false);
633 void ProfileSyncService::ShutdownImpl(bool sync_disabled) {
634 // First, we spin down the backend and wait for it to stop syncing completely
635 // before we Stop the data type manager. This is to avoid a late sync cycle
636 // applying changes to the sync db that wouldn't get applied via
637 // ChangeProcessors, leading to back-from-the-dead bugs.
638 base::Time shutdown_start_time = base::Time::Now();
639 if (backend_.get()) {
640 backend_->StopSyncingForShutdown();
643 // Stop all data type controllers, if needed. Note that until Stop
644 // completes, it is possible in theory to have a ChangeProcessor apply a
645 // change from a native model. In that case, it will get applied to the sync
646 // database (which doesn't get destroyed until we destroy the backend below)
647 // as an unsynced change. That will be persisted, and committed on restart.
648 if (data_type_manager_.get()) {
649 if (data_type_manager_->state() != DataTypeManager::STOPPED) {
650 // When aborting as part of shutdown, we should expect an aborted sync
651 // configure result, else we'll dcheck when we try to read the sync error.
652 expect_sync_configuration_aborted_ = true;
653 data_type_manager_->Stop();
655 data_type_manager_.reset();
658 // Shutdown the migrator before the backend to ensure it doesn't pull a null
659 // snapshot.
660 migrator_.reset();
661 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
663 // Move aside the backend so nobody else tries to use it while we are
664 // shutting it down.
665 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
666 if (doomed_backend.get()) {
667 doomed_backend->Shutdown(sync_disabled);
669 doomed_backend.reset();
671 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
672 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
674 weak_factory_.InvalidateWeakPtrs();
676 // Clear various flags.
677 expect_sync_configuration_aborted_ = false;
678 is_auth_in_progress_ = false;
679 backend_initialized_ = false;
680 // NULL if we're called from Shutdown().
681 if (invalidator_registrar_.get())
682 UpdateInvalidatorRegistrarState();
683 cached_passphrase_.clear();
684 encryption_pending_ = false;
685 encrypt_everything_ = false;
686 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
687 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
688 // Revert to "no auth error".
689 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
690 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
692 if (sync_global_error_.get()) {
693 GlobalErrorServiceFactory::GetForProfile(profile_)->RemoveGlobalError(
694 sync_global_error_.get());
695 RemoveObserver(sync_global_error_.get());
696 sync_global_error_.reset(NULL);
700 void ProfileSyncService::DisableForUser() {
701 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
702 // PSS clients don't think we're set up while we're shutting down.
703 sync_prefs_.ClearPreferences();
704 invalidator_storage_.Clear();
705 ClearUnrecoverableError();
706 ShutdownImpl(true);
707 NotifyObservers();
710 bool ProfileSyncService::HasSyncSetupCompleted() const {
711 return sync_prefs_.HasSyncSetupCompleted();
714 void ProfileSyncService::SetSyncSetupCompleted() {
715 sync_prefs_.SetSyncSetupCompleted();
718 void ProfileSyncService::UpdateLastSyncedTime() {
719 last_synced_time_ = base::Time::Now();
720 sync_prefs_.SetLastSyncedTime(last_synced_time_);
723 void ProfileSyncService::NotifyObservers() {
724 FOR_EACH_OBSERVER(Observer, observers_, OnStateChanged());
725 // TODO(akalin): Make an Observer subclass that listens and does the
726 // event routing.
727 sync_js_controller_.HandleJsEvent(
728 "onServiceStateChanged", JsEventDetails());
731 void ProfileSyncService::ClearStaleErrors() {
732 ClearUnrecoverableError();
733 last_actionable_error_ = SyncProtocolError();
734 // Clear the data type errors as well.
735 failed_datatypes_handler_.OnUserChoseDatatypes();
738 void ProfileSyncService::ClearUnrecoverableError() {
739 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
740 unrecoverable_error_message_.clear();
741 unrecoverable_error_location_ = tracked_objects::Location();
744 // static
745 // TODO(sync): Consider having syncer::Experiments provide this.
746 std::string ProfileSyncService::GetExperimentNameForDataType(
747 syncer::ModelType data_type) {
748 NOTREACHED();
749 return std::string();
752 void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) {
753 if (data_type_controllers_.count(data_type) > 0)
754 return;
755 NOTREACHED();
758 // An invariant has been violated. Transition to an error state where we try
759 // to do as little work as possible, to avoid further corruption or crashes.
760 void ProfileSyncService::OnUnrecoverableError(
761 const tracked_objects::Location& from_here,
762 const std::string& message) {
763 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
764 // interface are assumed to originate within the syncer.
765 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
766 OnUnrecoverableErrorImpl(from_here, message, true);
769 void ProfileSyncService::OnUnrecoverableErrorImpl(
770 const tracked_objects::Location& from_here,
771 const std::string& message,
772 bool delete_sync_database) {
773 DCHECK(HasUnrecoverableError());
774 unrecoverable_error_message_ = message;
775 unrecoverable_error_location_ = from_here;
777 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
778 unrecoverable_error_reason_,
779 ERROR_REASON_LIMIT);
780 NotifyObservers();
781 std::string location;
782 from_here.Write(true, true, &location);
783 LOG(ERROR)
784 << "Unrecoverable error detected at " << location
785 << " -- ProfileSyncService unusable: " << message;
787 // Shut all data types down.
788 MessageLoop::current()->PostTask(FROM_HERE,
789 base::Bind(&ProfileSyncService::ShutdownImpl, weak_factory_.GetWeakPtr(),
790 delete_sync_database));
793 void ProfileSyncService::DisableBrokenDatatype(
794 syncer::ModelType type,
795 const tracked_objects::Location& from_here,
796 std::string message) {
797 // First deactivate the type so that no further server changes are
798 // passed onto the change processor.
799 DeactivateDataType(type);
801 syncer::SyncError error(from_here, message, type);
803 std::list<syncer::SyncError> errors;
804 errors.push_back(error);
806 // Update this before posting a task. So if a configure happens before
807 // the task that we are going to post, this type would still be disabled.
808 failed_datatypes_handler_.UpdateFailedDatatypes(errors,
809 FailedDatatypesHandler::RUNTIME);
811 MessageLoop::current()->PostTask(FROM_HERE,
812 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager,
813 weak_factory_.GetWeakPtr()));
816 void ProfileSyncService::OnInvalidatorStateChange(
817 syncer::InvalidatorState state) {
818 invalidator_state_ = state;
819 UpdateInvalidatorRegistrarState();
822 void ProfileSyncService::OnIncomingInvalidation(
823 const syncer::ObjectIdInvalidationMap& invalidation_map) {
824 invalidator_registrar_->DispatchInvalidationsToHandlers(invalidation_map);
827 void ProfileSyncService::OnBackendInitialized(
828 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
829 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
830 debug_info_listener,
831 bool success) {
832 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
834 if (is_first_time_sync_configure_) {
835 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
836 } else {
837 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
840 DCHECK(!start_up_time_.is_null());
841 base::Time on_backend_initialized_time = base::Time::Now();
842 base::TimeDelta delta = on_backend_initialized_time - start_up_time_;
843 if (is_first_time_sync_configure_) {
844 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
845 } else {
846 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
848 start_up_time_ = base::Time();
850 if (!success) {
851 // Something went unexpectedly wrong. Play it safe: stop syncing at once
852 // and surface error UI to alert the user sync has stopped.
853 // Keep the directory around for now so that on restart we will retry
854 // again and potentially succeed in presence of transient file IO failures
855 // or permissions issues, etc.
857 // TODO(rlarocque): Consider making this UnrecoverableError less special.
858 // Unlike every other UnrecoverableError, it does not delete our sync data.
859 // This exception made sense at the time it was implemented, but our new
860 // directory corruption recovery mechanism makes it obsolete. By the time
861 // we get here, we will have already tried and failed to delete the
862 // directory. It would be no big deal if we tried to delete it again.
863 OnInternalUnrecoverableError(FROM_HERE,
864 "BackendInitialize failure",
865 false,
866 ERROR_REASON_BACKEND_INIT_FAILURE);
867 return;
870 backend_initialized_ = true;
871 UpdateInvalidatorRegistrarState();
873 sync_js_controller_.AttachJsBackend(js_backend);
874 debug_info_listener_ = debug_info_listener;
876 // If we have a cached passphrase use it to decrypt/encrypt data now that the
877 // backend is initialized. We want to call this before notifying observers in
878 // case this operation affects the "passphrase required" status.
879 ConsumeCachedPassphraseIfPossible();
881 // The very first time the backend initializes is effectively the first time
882 // we can say we successfully "synced". last_synced_time_ will only be null
883 // in this case, because the pref wasn't restored on StartUp.
884 if (last_synced_time_.is_null()) {
885 UpdateLastSyncedTime();
887 NotifyObservers();
889 if (auto_start_enabled_ && !FirstSetupInProgress()) {
890 // Backend is initialized but we're not in sync setup, so this must be an
891 // autostart - mark our sync setup as completed and we'll start syncing
892 // below.
893 SetSyncSetupCompleted();
894 NotifyObservers();
897 if (HasSyncSetupCompleted()) {
898 ConfigureDataTypeManager();
899 } else {
900 DCHECK(FirstSetupInProgress());
904 void ProfileSyncService::OnSyncCycleCompleted() {
905 UpdateLastSyncedTime();
906 if (GetSessionModelAssociator()) {
907 // Trigger garbage collection of old sessions now that we've downloaded
908 // any new session data. TODO(zea): Have this be a notification the session
909 // model associator listens too. Also consider somehow plumbing the current
910 // server time as last reported by CheckServerReachable, so we don't have to
911 // rely on the local clock, which may be off significantly.
912 MessageLoop::current()->PostTask(FROM_HERE,
913 base::Bind(&browser_sync::SessionModelAssociator::DeleteStaleSessions,
914 GetSessionModelAssociator()->AsWeakPtr()));
916 DVLOG(2) << "Notifying observers sync cycle completed";
917 NotifyObservers();
920 void ProfileSyncService::OnExperimentsChanged(
921 const syncer::Experiments& experiments) {
922 if (current_experiments_.Matches(experiments))
923 return;
925 // If this is a first time sync for a client, this will be called before
926 // OnBackendInitialized() to ensure the new datatypes are available at sync
927 // setup. As a result, the migrator won't exist yet. This is fine because for
928 // first time sync cases we're only concerned with making the datatype
929 // available.
930 if (migrator_.get() &&
931 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
932 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
933 return;
936 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
937 syncer::ModelTypeSet to_add;
938 const syncer::ModelTypeSet to_register =
939 Difference(to_add, registered_types);
940 DVLOG(2) << "OnExperimentsChanged called with types: "
941 << syncer::ModelTypeSetToString(to_add);
942 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register);
944 for (syncer::ModelTypeSet::Iterator it = to_register.First();
945 it.Good(); it.Inc()) {
946 // Received notice to enable experimental type. Check if the type is
947 // registered, and if not register a new datatype controller.
948 RegisterNewDataType(it.Get());
949 // Enable the about:flags switch for the experimental type so we don't have
950 // to always perform this reconfiguration. Once we set this, the type will
951 // remain registered on restart, so we will no longer go down this code
952 // path.
953 std::string experiment_name = GetExperimentNameForDataType(it.Get());
954 if (experiment_name.empty())
955 continue;
956 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
957 experiment_name,
958 true);
961 // Check if the user has "Keep Everything Synced" enabled. If so, we want
962 // to turn on all experimental types if they're not already on. Otherwise we
963 // leave them off.
964 // Note: if any types are already registered, we don't turn them on. This
965 // covers the case where we're already in the process of reconfiguring
966 // to turn an experimental type on.
967 if (sync_prefs_.HasKeepEverythingSynced()) {
968 // Mark all data types as preferred.
969 sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
971 // Only automatically turn on types if we have already finished set up.
972 // Otherwise, just leave the experimental types on by default.
973 if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_.get()) {
974 DVLOG(1) << "Dynamically enabling new datatypes: "
975 << syncer::ModelTypeSetToString(to_register);
976 OnMigrationNeededForTypes(to_register);
980 // Now enable any non-datatype features.
981 if (experiments.keystore_encryption) {
982 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
983 syncer::kKeystoreEncryptionFlag,
984 true);
987 if (experiments.full_history_sync) {
988 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
989 syncer::kFullHistorySyncFlag,
990 true);
993 if (experiments.favicon_sync) {
994 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
995 syncer::kFaviconSyncFlag,
996 true);
999 current_experiments_ = experiments;
1002 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1003 is_auth_in_progress_ = false;
1004 last_auth_error_ = error;
1006 // Fan the notification out to interested UI-thread components. Notify the
1007 // SigninGlobalError first so it reflects the latest auth state before we
1008 // notify observers.
1009 if (signin())
1010 signin()->signin_global_error()->AuthStatusChanged();
1011 NotifyObservers();
1014 namespace {
1016 AuthError ConnectionStatusToAuthError(
1017 syncer::ConnectionStatus status) {
1018 switch (status) {
1019 case syncer::CONNECTION_OK:
1020 return AuthError::AuthErrorNone();
1021 break;
1022 case syncer::CONNECTION_AUTH_ERROR:
1023 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1024 break;
1025 case syncer::CONNECTION_SERVER_ERROR:
1026 return AuthError(AuthError::CONNECTION_FAILED);
1027 break;
1028 default:
1029 NOTREACHED();
1030 return AuthError(AuthError::CONNECTION_FAILED);
1034 } // namespace
1036 void ProfileSyncService::OnConnectionStatusChange(
1037 syncer::ConnectionStatus status) {
1038 const GoogleServiceAuthError auth_error =
1039 ConnectionStatusToAuthError(status);
1040 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1041 UpdateAuthErrorState(auth_error);
1044 void ProfileSyncService::OnStopSyncingPermanently() {
1045 UpdateAuthErrorState(AuthError(AuthError::SERVICE_UNAVAILABLE));
1046 sync_prefs_.SetStartSuppressed(true);
1047 DisableForUser();
1048 // If signout is allowed, signout the user on a dashboard clear.
1049 if (!auto_start_enabled_) // Skip signout on ChromeOS/Android.
1050 signin_->SignOut();
1053 void ProfileSyncService::OnPassphraseRequired(
1054 syncer::PassphraseRequiredReason reason,
1055 const sync_pb::EncryptedData& pending_keys) {
1056 DCHECK(backend_.get());
1057 DCHECK(backend_->IsNigoriEnabled());
1059 // TODO(lipalani) : add this check to other locations as well.
1060 if (HasUnrecoverableError()) {
1061 // When unrecoverable error is detected we post a task to shutdown the
1062 // backend. The task might not have executed yet.
1063 return;
1066 DVLOG(1) << "Passphrase required with reason: "
1067 << syncer::PassphraseRequiredReasonToString(reason);
1068 passphrase_required_reason_ = reason;
1070 // Notify observers that the passphrase status may have changed.
1071 NotifyObservers();
1074 void ProfileSyncService::OnPassphraseAccepted() {
1075 DVLOG(1) << "Received OnPassphraseAccepted.";
1077 // If the pending keys were resolved via keystore, it's possible we never
1078 // consumed our cached passphrase. Clear it now.
1079 if (!cached_passphrase_.empty())
1080 cached_passphrase_.clear();
1082 // Reset passphrase_required_reason_ since we know we no longer require the
1083 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1084 // because that can be called by OnPassphraseRequired() if no encrypted data
1085 // types are enabled, and we don't want to clobber the true passphrase error.
1086 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1088 #if defined(OS_ANDROID)
1089 // Re-enable passwords if we have disabled them.
1090 if (failed_datatypes_handler_.GetFailedTypes().Has(syncer::PASSWORDS) &&
1091 ShouldEnablePasswordSyncForAndroid()) {
1092 // Clear the data type errors.
1093 failed_datatypes_handler_.OnUserChoseDatatypes();
1095 #endif
1097 // Make sure the data types that depend on the passphrase are started at
1098 // this time.
1099 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1101 if (data_type_manager_.get()) {
1102 // Unblock the data type manager if necessary.
1103 data_type_manager_->Configure(types,
1104 syncer::CONFIGURE_REASON_RECONFIGURATION);
1107 NotifyObservers();
1110 void ProfileSyncService::OnEncryptedTypesChanged(
1111 syncer::ModelTypeSet encrypted_types,
1112 bool encrypt_everything) {
1113 encrypted_types_ = encrypted_types;
1114 encrypt_everything_ = encrypt_everything;
1115 DVLOG(1) << "Encrypted types changed to "
1116 << syncer::ModelTypeSetToString(encrypted_types_)
1117 << " (encrypt everything is set to "
1118 << (encrypt_everything_ ? "true" : "false") << ")";
1119 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1122 void ProfileSyncService::OnEncryptionComplete() {
1123 DVLOG(1) << "Encryption complete";
1124 if (encryption_pending_ && encrypt_everything_) {
1125 encryption_pending_ = false;
1126 // This is to nudge the integration tests when encryption is
1127 // finished.
1128 NotifyObservers();
1132 void ProfileSyncService::OnMigrationNeededForTypes(
1133 syncer::ModelTypeSet types) {
1134 DCHECK(backend_initialized_);
1135 DCHECK(data_type_manager_.get());
1137 // Migrator must be valid, because we don't sync until it is created and this
1138 // callback originates from a sync cycle.
1139 migrator_->MigrateTypes(types);
1142 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1143 last_actionable_error_ = error;
1144 DCHECK_NE(last_actionable_error_.action,
1145 syncer::UNKNOWN_ACTION);
1146 switch (error.action) {
1147 case syncer::UPGRADE_CLIENT:
1148 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1149 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1150 case syncer::STOP_AND_RESTART_SYNC:
1151 // TODO(lipalani) : if setup in progress we want to display these
1152 // actions in the popup. The current experience might not be optimal for
1153 // the user. We just dismiss the dialog.
1154 if (setup_in_progress_) {
1155 OnStopSyncingPermanently();
1156 expect_sync_configuration_aborted_ = true;
1158 // Trigger an unrecoverable error to stop syncing.
1159 OnInternalUnrecoverableError(FROM_HERE,
1160 last_actionable_error_.error_description,
1161 true,
1162 ERROR_REASON_ACTIONABLE_ERROR);
1163 break;
1164 case syncer::DISABLE_SYNC_ON_CLIENT:
1165 OnStopSyncingPermanently();
1166 break;
1167 default:
1168 NOTREACHED();
1170 NotifyObservers();
1173 void ProfileSyncService::OnConfigureBlocked() {
1174 NotifyObservers();
1177 void ProfileSyncService::OnConfigureDone(
1178 const browser_sync::DataTypeManager::ConfigureResult& result) {
1179 // We should have cleared our cached passphrase before we get here (in
1180 // OnBackendInitialized()).
1181 DCHECK(cached_passphrase_.empty());
1183 if (!sync_configure_start_time_.is_null()) {
1184 if (result.status == DataTypeManager::OK ||
1185 result.status == DataTypeManager::PARTIAL_SUCCESS) {
1186 base::Time sync_configure_stop_time = base::Time::Now();
1187 base::TimeDelta delta = sync_configure_stop_time -
1188 sync_configure_start_time_;
1189 if (is_first_time_sync_configure_) {
1190 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1191 } else {
1192 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1193 delta);
1196 sync_configure_start_time_ = base::Time();
1199 // Notify listeners that configuration is done.
1200 content::NotificationService::current()->Notify(
1201 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1202 content::Source<ProfileSyncService>(this),
1203 content::NotificationService::NoDetails());
1205 configure_status_ = result.status;
1206 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1207 // The possible status values:
1208 // ABORT - Configuration was aborted. This is not an error, if
1209 // initiated by user.
1210 // OK - Everything succeeded.
1211 // PARTIAL_SUCCESS - Some datatypes failed to start.
1212 // Everything else is an UnrecoverableError. So treat it as such.
1214 // First handle the abort case.
1215 if (configure_status_ == DataTypeManager::ABORTED &&
1216 expect_sync_configuration_aborted_) {
1217 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1218 expect_sync_configuration_aborted_ = false;
1219 return;
1222 // Handle unrecoverable error.
1223 if (configure_status_ != DataTypeManager::OK &&
1224 configure_status_ != DataTypeManager::PARTIAL_SUCCESS) {
1225 // Something catastrophic had happened. We should only have one
1226 // error representing it.
1227 DCHECK_EQ(result.failed_data_types.size(),
1228 static_cast<unsigned int>(1));
1229 syncer::SyncError error = result.failed_data_types.front();
1230 DCHECK(error.IsSet());
1231 std::string message =
1232 "Sync configuration failed with status " +
1233 DataTypeManager::ConfigureStatusToString(configure_status_) +
1234 " during " + syncer::ModelTypeToString(error.type()) +
1235 ": " + error.message();
1236 LOG(ERROR) << "ProfileSyncService error: "
1237 << message;
1238 OnInternalUnrecoverableError(error.location(),
1239 message,
1240 true,
1241 ERROR_REASON_CONFIGURATION_FAILURE);
1242 return;
1245 // Now handle partial success and full success.
1246 MessageLoop::current()->PostTask(FROM_HERE,
1247 base::Bind(&ProfileSyncService::OnSyncConfigureDone,
1248 weak_factory_.GetWeakPtr(), result));
1250 // We should never get in a state where we have no encrypted datatypes
1251 // enabled, and yet we still think we require a passphrase for decryption.
1252 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1253 !IsEncryptedDatatypeEnabled()));
1255 // This must be done before we start syncing with the server to avoid
1256 // sending unencrypted data up on a first time sync.
1257 if (encryption_pending_)
1258 backend_->EnableEncryptEverything();
1259 NotifyObservers();
1261 if (migrator_.get() &&
1262 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1263 // Migration in progress. Let the migrator know we just finished
1264 // configuring something. It will be up to the migrator to call
1265 // StartSyncingWithServer() if migration is now finished.
1266 migrator_->OnConfigureDone(result);
1267 } else {
1268 StartSyncingWithServer();
1272 void ProfileSyncService::OnConfigureRetry() {
1273 // We should have cleared our cached passphrase before we get here (in
1274 // OnBackendInitialized()).
1275 DCHECK(cached_passphrase_.empty());
1277 OnSyncConfigureRetry();
1280 void ProfileSyncService::OnConfigureStart() {
1281 sync_configure_start_time_ = base::Time::Now();
1282 content::NotificationService::current()->Notify(
1283 chrome::NOTIFICATION_SYNC_CONFIGURE_START,
1284 content::Source<ProfileSyncService>(this),
1285 content::NotificationService::NoDetails());
1286 NotifyObservers();
1289 std::string ProfileSyncService::QuerySyncStatusSummary() {
1290 if (HasUnrecoverableError()) {
1291 return "Unrecoverable error detected";
1292 } else if (!backend_.get()) {
1293 return "Syncing not enabled";
1294 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1295 return "First time sync setup incomplete";
1296 } else if (backend_.get() && HasSyncSetupCompleted() &&
1297 data_type_manager_.get() &&
1298 data_type_manager_->state() != DataTypeManager::CONFIGURED) {
1299 return "Datatypes not fully initialized";
1300 } else if (ShouldPushChanges()) {
1301 return "Sync service initialized";
1302 } else {
1303 return "Status unknown: Internal error?";
1307 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1308 if (sync_initialized())
1309 return "Done";
1310 else if (!start_up_time_.is_null())
1311 return "Deferred";
1312 else
1313 return "Not started";
1316 bool ProfileSyncService::QueryDetailedSyncStatus(
1317 SyncBackendHost::Status* result) {
1318 if (backend_.get() && backend_initialized_) {
1319 *result = backend_->GetDetailedStatus();
1320 return true;
1321 } else {
1322 SyncBackendHost::Status status;
1323 status.sync_protocol_error = last_actionable_error_;
1324 *result = status;
1325 return false;
1329 const AuthError& ProfileSyncService::GetAuthError() const {
1330 return last_auth_error_;
1333 GoogleServiceAuthError ProfileSyncService::GetAuthStatus() const {
1334 return GetAuthError();
1337 bool ProfileSyncService::FirstSetupInProgress() const {
1338 return !HasSyncSetupCompleted() && setup_in_progress_;
1341 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1342 bool was_in_progress = setup_in_progress_;
1343 setup_in_progress_ = setup_in_progress;
1344 if (!setup_in_progress && was_in_progress) {
1345 if (sync_initialized()) {
1346 ReconfigureDatatypeManager();
1349 NotifyObservers();
1352 bool ProfileSyncService::sync_initialized() const {
1353 return backend_initialized_;
1356 bool ProfileSyncService::waiting_for_auth() const {
1357 return is_auth_in_progress_;
1360 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1361 return current_experiments_;
1364 bool ProfileSyncService::HasUnrecoverableError() const {
1365 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1368 bool ProfileSyncService::IsPassphraseRequired() const {
1369 return passphrase_required_reason_ !=
1370 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1373 // TODO(zea): Rename this IsPassphraseNeededFromUI and ensure it's used
1374 // appropriately (see http://crbug.com/91379).
1375 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1376 // If there is an encrypted datatype enabled and we don't have the proper
1377 // passphrase, we must prompt the user for a passphrase. The only way for the
1378 // user to avoid entering their passphrase is to disable the encrypted types.
1379 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1382 string16 ProfileSyncService::GetLastSyncedTimeString() const {
1383 if (last_synced_time_.is_null())
1384 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1386 base::TimeDelta last_synced = base::Time::Now() - last_synced_time_;
1388 if (last_synced < base::TimeDelta::FromMinutes(1))
1389 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1391 return TimeFormat::TimeElapsed(last_synced);
1394 void ProfileSyncService::UpdateSelectedTypesHistogram(
1395 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1396 if (!HasSyncSetupCompleted() ||
1397 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1398 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1401 // Only log the data types that are shown in the sync settings ui.
1402 // Note: the order of these types must match the ordering of
1403 // the respective types in ModelType
1404 const browser_sync::user_selectable_type::UserSelectableSyncType
1405 user_selectable_types[] = {
1406 browser_sync::user_selectable_type::BOOKMARKS,
1407 browser_sync::user_selectable_type::PREFERENCES,
1408 browser_sync::user_selectable_type::PASSWORDS,
1409 browser_sync::user_selectable_type::AUTOFILL,
1410 browser_sync::user_selectable_type::THEMES,
1411 browser_sync::user_selectable_type::TYPED_URLS,
1412 browser_sync::user_selectable_type::EXTENSIONS,
1413 browser_sync::user_selectable_type::APPS,
1414 browser_sync::user_selectable_type::PROXY_TABS
1417 COMPILE_ASSERT(26 == syncer::MODEL_TYPE_COUNT, UpdateCustomConfigHistogram);
1419 if (!sync_everything) {
1420 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1422 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1423 syncer::ModelTypeSet::Iterator it = type_set.First();
1425 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1427 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1428 ++i, it.Inc()) {
1429 const syncer::ModelType type = it.Get();
1430 if (chosen_types.Has(type) &&
1431 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1432 // Selected type has changed - log it.
1433 UMA_HISTOGRAM_ENUMERATION(
1434 "Sync.CustomSync",
1435 user_selectable_types[i],
1436 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1442 #if defined(OS_CHROMEOS)
1443 void ProfileSyncService::RefreshSpareBootstrapToken(
1444 const std::string& passphrase) {
1445 browser_sync::ChromeEncryptor encryptor;
1446 syncer::Cryptographer temp_cryptographer(&encryptor);
1447 // The first 2 params (hostname and username) doesn't have any effect here.
1448 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1450 std::string bootstrap_token;
1451 if (!temp_cryptographer.AddKey(key_params)) {
1452 NOTREACHED() << "Failed to add key to cryptographer.";
1454 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1455 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1457 #endif
1459 void ProfileSyncService::OnUserChoseDatatypes(
1460 bool sync_everything,
1461 syncer::ModelTypeSet chosen_types) {
1462 if (!backend_.get() && !HasUnrecoverableError()) {
1463 NOTREACHED();
1464 return;
1467 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1468 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1470 failed_datatypes_handler_.OnUserChoseDatatypes();
1471 ChangePreferredDataTypes(chosen_types);
1472 AcknowledgeSyncedTypes();
1473 NotifyObservers();
1476 void ProfileSyncService::ChangePreferredDataTypes(
1477 syncer::ModelTypeSet preferred_types) {
1479 DVLOG(1) << "ChangePreferredDataTypes invoked";
1480 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1481 const syncer::ModelTypeSet registered_preferred_types =
1482 Intersection(registered_types, preferred_types);
1483 sync_prefs_.SetPreferredDataTypes(registered_types,
1484 registered_preferred_types);
1486 // Now reconfigure the DTM.
1487 ReconfigureDatatypeManager();
1490 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1491 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1492 const syncer::ModelTypeSet preferred_types =
1493 sync_prefs_.GetPreferredDataTypes(registered_types);
1494 const syncer::ModelTypeSet failed_types =
1495 failed_datatypes_handler_.GetFailedTypes();
1496 return Difference(preferred_types, failed_types);
1499 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1500 syncer::ModelTypeSet registered_types;
1501 // The data_type_controllers_ are determined by command-line flags; that's
1502 // effectively what controls the values returned here.
1503 for (DataTypeController::TypeMap::const_iterator it =
1504 data_type_controllers_.begin();
1505 it != data_type_controllers_.end(); ++it) {
1506 registered_types.Put(it->first);
1508 return registered_types;
1511 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1512 syncer::PassphraseType passphrase_type = GetPassphraseType();
1513 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1514 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1517 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1518 return backend_->GetPassphraseType();
1521 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1522 return backend_->GetExplicitPassphraseTime();
1525 bool ProfileSyncService::IsCryptographerReady(
1526 const syncer::BaseTransaction* trans) const {
1527 return backend_.get() && backend_->IsCryptographerReady(trans);
1530 SyncBackendHost* ProfileSyncService::GetBackendForTest() {
1531 // We don't check |backend_initialized_|; we assume the test class
1532 // knows what it's doing.
1533 return backend_.get();
1536 void ProfileSyncService::ConfigurePriorityDataTypes() {
1537 const syncer::ModelTypeSet priority_types =
1538 Intersection(GetPreferredDataTypes(), syncer::PriorityUserTypes());
1539 if (!priority_types.Empty()) {
1540 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1541 syncer::CONFIGURE_REASON_RECONFIGURATION :
1542 syncer::CONFIGURE_REASON_NEW_CLIENT;
1543 data_type_manager_->Configure(priority_types, reason);
1547 void ProfileSyncService::ConfigureDataTypeManager() {
1548 // Don't configure datatypes if the setup UI is still on the screen - this
1549 // is to help multi-screen setting UIs (like iOS) where they don't want to
1550 // start syncing data until the user is done configuring encryption options,
1551 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1552 // SetSetupInProgress(false).
1553 if (setup_in_progress_)
1554 return;
1556 bool restart = false;
1557 if (!data_type_manager_.get()) {
1558 restart = true;
1559 data_type_manager_.reset(
1560 factory_->CreateDataTypeManager(debug_info_listener_,
1561 backend_.get(),
1562 &data_type_controllers_,
1563 this,
1564 &failed_datatypes_handler_));
1566 // We create the migrator at the same time.
1567 migrator_.reset(
1568 new browser_sync::BackendMigrator(
1569 profile_->GetDebugName(), GetUserShare(),
1570 this, data_type_manager_.get(),
1571 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1572 base::Unretained(this))));
1575 // This is probably where we want to trigger configuration of priority
1576 // datatypes, but we need to resolve crbug.com/226195 first.
1578 #if defined(OS_ANDROID)
1579 if (GetPreferredDataTypes().Has(syncer::PASSWORDS) &&
1580 !ShouldEnablePasswordSyncForAndroid()) {
1581 DisableBrokenDatatype(syncer::PASSWORDS, FROM_HERE, "Not supported.");
1583 #endif
1585 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1586 if (IsPassphraseRequiredForDecryption()) {
1587 // We need a passphrase still. We don't bother to attempt to configure
1588 // until we receive an OnPassphraseAccepted (which triggers a configure).
1589 DVLOG(1) << "ProfileSyncService::ConfigureDataTypeManager bailing out "
1590 << "because a passphrase required";
1591 NotifyObservers();
1592 return;
1594 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1595 if (!HasSyncSetupCompleted()) {
1596 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1597 } else if (restart) {
1598 // Datatype downloads on restart are generally due to newly supported
1599 // datatypes (although it's also possible we're picking up where a failed
1600 // previous configuration left off).
1601 // TODO(sync): consider detecting configuration recovery and setting
1602 // the reason here appropriately.
1603 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1604 } else {
1605 // The user initiated a reconfiguration (either to add or remove types).
1606 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1609 data_type_manager_->Configure(types, reason);
1612 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1613 if (backend_.get() && backend_initialized_) {
1614 return backend_->GetUserShare();
1616 NOTREACHED();
1617 return NULL;
1620 syncer::sessions::SyncSessionSnapshot
1621 ProfileSyncService::GetLastSessionSnapshot() const {
1622 if (backend_.get() && backend_initialized_) {
1623 return backend_->GetLastSessionSnapshot();
1625 NOTREACHED();
1626 return syncer::sessions::SyncSessionSnapshot();
1629 bool ProfileSyncService::HasUnsyncedItems() const {
1630 if (backend_.get() && backend_initialized_) {
1631 return backend_->HasUnsyncedItems();
1633 NOTREACHED();
1634 return false;
1637 browser_sync::BackendMigrator*
1638 ProfileSyncService::GetBackendMigratorForTest() {
1639 return migrator_.get();
1642 void ProfileSyncService::GetModelSafeRoutingInfo(
1643 syncer::ModelSafeRoutingInfo* out) const {
1644 if (backend_.get() && backend_initialized_) {
1645 backend_->GetModelSafeRoutingInfo(out);
1646 } else {
1647 NOTREACHED();
1651 Value* ProfileSyncService::GetTypeStatusMap() const {
1652 scoped_ptr<ListValue> result(new ListValue());
1654 if (!backend_.get() || !backend_initialized_) {
1655 return result.release();
1658 std::vector<syncer::SyncError> errors =
1659 failed_datatypes_handler_.GetAllErrors();
1660 std::map<ModelType, syncer::SyncError> error_map;
1661 for (std::vector<syncer::SyncError>::iterator it = errors.begin();
1662 it != errors.end(); ++it) {
1663 error_map[it->type()] = *it;
1666 ModelTypeSet active_types;
1667 ModelTypeSet passive_types;
1668 ModelSafeRoutingInfo routing_info;
1669 backend_->GetModelSafeRoutingInfo(&routing_info);
1670 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1671 it != routing_info.end(); ++it) {
1672 if (it->second == syncer::GROUP_PASSIVE) {
1673 passive_types.Put(it->first);
1674 } else {
1675 active_types.Put(it->first);
1679 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
1680 ModelTypeSet &throttled_types(detailed_status.throttled_types);
1681 ModelTypeSet registered = GetRegisteredDataTypes();
1682 scoped_ptr<DictionaryValue> type_status_header(new DictionaryValue());
1684 type_status_header->SetString("name", "Model Type");
1685 type_status_header->SetString("status", "header");
1686 type_status_header->SetString("value", "Group Type");
1687 type_status_header->SetString("num_entries", "Total Entries");
1688 type_status_header->SetString("num_live", "Live Entries");
1689 result->Append(type_status_header.release());
1691 scoped_ptr<DictionaryValue> type_status;
1692 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
1693 ModelType type = it.Get();
1695 type_status.reset(new DictionaryValue());
1696 type_status->SetString("name", ModelTypeToString(type));
1698 if (error_map.find(type) != error_map.end()) {
1699 const syncer::SyncError &error = error_map.find(type)->second;
1700 DCHECK(error.IsSet());
1701 std::string error_text = "Error: " + error.location().ToString() +
1702 ", " + error.message();
1703 type_status->SetString("status", "error");
1704 type_status->SetString("value", error_text);
1705 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
1706 type_status->SetString("status", "warning");
1707 type_status->SetString("value", "Passive, Throttled");
1708 } else if (passive_types.Has(type)) {
1709 type_status->SetString("status", "warning");
1710 type_status->SetString("value", "Passive");
1711 } else if (throttled_types.Has(type)) {
1712 type_status->SetString("status", "warning");
1713 type_status->SetString("value", "Throttled");
1714 } else if (active_types.Has(type)) {
1715 type_status->SetString("status", "ok");
1716 type_status->SetString("value", "Active: " +
1717 ModelSafeGroupToString(routing_info[type]));
1718 } else {
1719 type_status->SetString("status", "warning");
1720 type_status->SetString("value", "Disabled by User");
1723 int live_count = detailed_status.num_entries_by_type[type] -
1724 detailed_status.num_to_delete_entries_by_type[type];
1725 type_status->SetInteger("num_entries",
1726 detailed_status.num_entries_by_type[type]);
1727 type_status->SetInteger("num_live", live_count);
1729 result->Append(type_status.release());
1731 return result.release();
1734 void ProfileSyncService::ActivateDataType(
1735 syncer::ModelType type, syncer::ModelSafeGroup group,
1736 ChangeProcessor* change_processor) {
1737 if (!backend_.get()) {
1738 NOTREACHED();
1739 return;
1741 DCHECK(backend_initialized_);
1742 backend_->ActivateDataType(type, group, change_processor);
1745 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
1746 if (!backend_.get())
1747 return;
1748 backend_->DeactivateDataType(type);
1751 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
1752 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
1753 // If the backend isn't running yet, OnBackendInitialized() will call this
1754 // method again after the backend starts up.
1755 if (cached_passphrase_.empty() || !sync_initialized())
1756 return;
1758 // Backend is up and running, so we can consume the cached passphrase.
1759 std::string passphrase = cached_passphrase_;
1760 cached_passphrase_.clear();
1762 // If we need a passphrase to decrypt data, try the cached passphrase.
1763 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
1764 if (SetDecryptionPassphrase(passphrase)) {
1765 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
1766 return;
1770 // If we get here, we don't have pending keys (or at least, the passphrase
1771 // doesn't decrypt them) - just try to re-encrypt using the encryption
1772 // passphrase.
1773 if (!IsUsingSecondaryPassphrase())
1774 SetEncryptionPassphrase(passphrase, IMPLICIT);
1777 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
1778 PassphraseType type) {
1779 // This should only be called when the backend has been initialized.
1780 DCHECK(sync_initialized());
1781 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
1782 "Data is already encrypted using an explicit passphrase";
1783 DCHECK(!(type == EXPLICIT &&
1784 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
1785 "Can not set explicit passphrase when decryption is needed.";
1787 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
1788 << " passphrase for encryption.";
1789 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
1790 // REASON_ENCRYPTION implies that the cryptographer does not have pending
1791 // keys. Hence, as long as we're not trying to do an invalid passphrase
1792 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
1793 // will succeed. If for some reason a new encryption key arrives via
1794 // sync later, the SBH will trigger another OnPassphraseRequired().
1795 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1796 NotifyObservers();
1798 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
1801 bool ProfileSyncService::SetDecryptionPassphrase(
1802 const std::string& passphrase) {
1803 if (IsPassphraseRequired()) {
1804 DVLOG(1) << "Setting passphrase for decryption.";
1805 return backend_->SetDecryptionPassphrase(passphrase);
1806 } else {
1807 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
1808 "IsPassphraseRequired() is false.";
1809 return false;
1813 void ProfileSyncService::EnableEncryptEverything() {
1814 // Tests override sync_initialized() to always return true, so we
1815 // must check that instead of |backend_initialized_|.
1816 // TODO(akalin): Fix the above. :/
1817 DCHECK(sync_initialized());
1818 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
1819 // problems around cancelling encryption in the background (crbug.com/119649).
1820 if (!encrypt_everything_)
1821 encryption_pending_ = true;
1824 bool ProfileSyncService::encryption_pending() const {
1825 // We may be called during the setup process before we're
1826 // initialized (via IsEncryptedDatatypeEnabled and
1827 // IsPassphraseRequiredForDecryption).
1828 return encryption_pending_;
1831 bool ProfileSyncService::EncryptEverythingEnabled() const {
1832 DCHECK(backend_initialized_);
1833 return encrypt_everything_ || encryption_pending_;
1836 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
1837 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1838 // We may be called during the setup process before we're
1839 // initialized. In this case, we default to the sensitive types.
1840 return encrypted_types_;
1843 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
1844 NotifyObservers();
1845 if (is_sync_managed) {
1846 DisableForUser();
1847 } else {
1848 // Sync is no longer disabled by policy. Try starting it up if appropriate.
1849 TryStart();
1853 void ProfileSyncService::Observe(int type,
1854 const content::NotificationSource& source,
1855 const content::NotificationDetails& details) {
1856 switch (type) {
1857 case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL: {
1858 const GoogleServiceSigninSuccessDetails* successful =
1859 content::Details<const GoogleServiceSigninSuccessDetails>(
1860 details).ptr();
1861 if (!sync_prefs_.IsStartSuppressed() &&
1862 !successful->password.empty()) {
1863 cached_passphrase_ = successful->password;
1864 // Try to consume the passphrase we just cached. If the sync backend
1865 // is not running yet, the passphrase will remain cached until the
1866 // backend starts up.
1867 ConsumeCachedPassphraseIfPossible();
1869 #if defined(OS_CHROMEOS)
1870 RefreshSpareBootstrapToken(successful->password);
1871 #endif
1872 if (!sync_initialized() ||
1873 GetAuthError().state() != AuthError::NONE) {
1874 // Track the fact that we're still waiting for auth to complete.
1875 is_auth_in_progress_ = true;
1877 break;
1879 case chrome::NOTIFICATION_TOKEN_REQUEST_FAILED: {
1880 const TokenService::TokenRequestFailedDetails& token_details =
1881 *(content::Details<const TokenService::TokenRequestFailedDetails>(
1882 details).ptr());
1883 if (IsTokenServiceRelevant(token_details.service()) &&
1884 !IsSyncTokenAvailable()) {
1885 // The additional check around IsSyncTokenAvailable() above prevents us
1886 // sounding the alarm if we actually have a valid token but a refresh
1887 // attempt by TokenService failed for any variety of reasons (e.g. flaky
1888 // network). It's possible the token we do have is also invalid, but in
1889 // that case we should already have (or can expect) an auth error sent
1890 // from the sync backend.
1891 AuthError error(AuthError::INVALID_GAIA_CREDENTIALS);
1892 UpdateAuthErrorState(error);
1894 break;
1896 case chrome::NOTIFICATION_TOKEN_AVAILABLE: {
1897 const TokenService::TokenAvailableDetails& token_details =
1898 *(content::Details<const TokenService::TokenAvailableDetails>(
1899 details).ptr());
1900 if (!IsTokenServiceRelevant(token_details.service()))
1901 break;
1902 } // Fall through.
1903 case chrome::NOTIFICATION_TOKEN_LOADING_FINISHED: {
1904 // This notification gets fired when TokenService loads the tokens
1905 // from storage.
1906 // Initialize the backend if sync is enabled. If the sync token was
1907 // not loaded, GetCredentials() will generate invalid credentials to
1908 // cause the backend to generate an auth error (crbug.com/121755).
1909 if (backend_.get())
1910 backend_->UpdateCredentials(GetCredentials());
1911 else
1912 TryStart();
1913 break;
1915 case chrome::NOTIFICATION_TOKENS_CLEARED: {
1916 // GetCredentials() will generate invalid credentials to cause the backend
1917 // to generate an auth error.
1918 if (backend_.get())
1919 backend_->UpdateCredentials(GetCredentials());
1920 break;
1922 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT:
1923 // Disable sync if the user is signed out.
1924 DisableForUser();
1925 break;
1926 default: {
1927 NOTREACHED();
1932 void ProfileSyncService::AddObserver(Observer* observer) {
1933 observers_.AddObserver(observer);
1936 void ProfileSyncService::RemoveObserver(Observer* observer) {
1937 observers_.RemoveObserver(observer);
1940 bool ProfileSyncService::HasObserver(Observer* observer) const {
1941 return observers_.HasObserver(observer);
1944 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
1945 return sync_js_controller_.AsWeakPtr();
1948 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
1949 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
1952 // static
1953 bool ProfileSyncService::IsSyncEnabled() {
1954 // We have switches::kEnableSync just in case we need to change back to
1955 // sync-disabled-by-default on a platform.
1956 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync);
1959 bool ProfileSyncService::IsManaged() const {
1960 return sync_prefs_.IsManaged();
1963 bool ProfileSyncService::ShouldPushChanges() {
1964 // True only after all bootstrapping has succeeded: the sync backend
1965 // is initialized, all enabled data types are consistent with one
1966 // another, and no unrecoverable error has transpired.
1967 if (HasUnrecoverableError())
1968 return false;
1970 if (!data_type_manager_.get())
1971 return false;
1973 return data_type_manager_->state() == DataTypeManager::CONFIGURED;
1976 void ProfileSyncService::StopAndSuppress() {
1977 sync_prefs_.SetStartSuppressed(true);
1978 ShutdownImpl(false);
1981 bool ProfileSyncService::IsStartSuppressed() const {
1982 return sync_prefs_.IsStartSuppressed();
1985 void ProfileSyncService::UnsuppressAndStart() {
1986 DCHECK(profile_);
1987 sync_prefs_.SetStartSuppressed(false);
1988 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess
1989 // is never called for some clients.
1990 if (signin_ && signin_->GetAuthenticatedUsername().empty()) {
1991 signin_->SetAuthenticatedUsername(sync_prefs_.GetGoogleServicesUsername());
1993 TryStart();
1996 void ProfileSyncService::AcknowledgeSyncedTypes() {
1997 sync_prefs_.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2000 void ProfileSyncService::ReconfigureDatatypeManager() {
2001 // If we haven't initialized yet, don't configure the DTM as it could cause
2002 // association to start before a Directory has even been created.
2003 if (backend_initialized_) {
2004 DCHECK(backend_.get());
2005 ConfigureDataTypeManager();
2006 } else if (HasUnrecoverableError()) {
2007 // There is nothing more to configure. So inform the listeners,
2008 NotifyObservers();
2010 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2011 << "Unrecoverable error.";
2012 } else {
2013 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2014 << "initialized";
2018 const FailedDatatypesHandler& ProfileSyncService::failed_datatypes_handler()
2019 const {
2020 return failed_datatypes_handler_;
2023 void ProfileSyncService::OnInternalUnrecoverableError(
2024 const tracked_objects::Location& from_here,
2025 const std::string& message,
2026 bool delete_sync_database,
2027 UnrecoverableErrorReason reason) {
2028 DCHECK(!HasUnrecoverableError());
2029 unrecoverable_error_reason_ = reason;
2030 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2033 void ProfileSyncService::UpdateInvalidatorRegistrarState() {
2034 const syncer::InvalidatorState effective_state =
2035 backend_initialized_ ?
2036 invalidator_state_ : syncer::TRANSIENT_INVALIDATION_ERROR;
2037 DVLOG(1) << "New invalidator state: "
2038 << syncer::InvalidatorStateToString(invalidator_state_)
2039 << ", effective state: "
2040 << syncer::InvalidatorStateToString(effective_state);
2041 invalidator_registrar_->UpdateInvalidatorState(effective_state);
2044 void ProfileSyncService::ResetForTest() {
2045 Profile* profile = profile_;
2046 SigninManager* signin = SigninManagerFactory::GetForProfile(profile);
2047 ProfileSyncService::StartBehavior behavior =
2048 browser_defaults::kSyncAutoStarts ? ProfileSyncService::AUTO_START
2049 : ProfileSyncService::MANUAL_START;
2051 // We call the destructor and placement new here because we want to explicitly
2052 // recreate a new ProfileSyncService instance at the same memory location as
2053 // the old one. Doing so is fine because this code is run only from within
2054 // integration tests, and the message loop is not running at this point.
2055 // See http://stackoverflow.com/questions/6224121/is-new-this-myclass-undefined-behaviour-after-directly-calling-the-destru.
2056 ProfileSyncService* old_this = this;
2057 this->~ProfileSyncService();
2058 new(old_this) ProfileSyncService(
2059 new ProfileSyncComponentsFactoryImpl(profile,
2060 CommandLine::ForCurrentProcess()),
2061 profile,
2062 signin,
2063 behavior);