Use AuthError consistently
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blob542d731c29a6ef7397f6efd315583aae003d9cdf
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/profiles/profile.h"
30 #include "chrome/browser/signin/signin_manager.h"
31 #include "chrome/browser/signin/signin_manager_factory.h"
32 #include "chrome/browser/signin/token_service.h"
33 #include "chrome/browser/signin/token_service_factory.h"
34 #include "chrome/browser/sync/backend_migrator.h"
35 #include "chrome/browser/sync/glue/change_processor.h"
36 #include "chrome/browser/sync/glue/chrome_encryptor.h"
37 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
38 #include "chrome/browser/sync/glue/data_type_controller.h"
39 #include "chrome/browser/sync/glue/session_data_type_controller.h"
40 #include "chrome/browser/sync/glue/session_model_associator.h"
41 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
42 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
43 #include "chrome/browser/sync/sync_global_error.h"
44 #include "chrome/browser/sync/user_selectable_sync_type.h"
45 #include "chrome/browser/ui/browser.h"
46 #include "chrome/browser/ui/browser_list.h"
47 #include "chrome/browser/ui/browser_window.h"
48 #include "chrome/browser/ui/global_error/global_error_service.h"
49 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
50 #include "chrome/common/chrome_notification_types.h"
51 #include "chrome/common/chrome_switches.h"
52 #include "chrome/common/chrome_version_info.h"
53 #include "chrome/common/time_format.h"
54 #include "chrome/common/url_constants.h"
55 #include "content/public/browser/notification_details.h"
56 #include "content/public/browser/notification_service.h"
57 #include "content/public/browser/notification_source.h"
58 #include "google_apis/gaia/gaia_constants.h"
59 #include "grit/generated_resources.h"
60 #include "net/cookies/cookie_monster.h"
61 #include "sync/api/sync_error.h"
62 #include "sync/internal_api/public/configure_reason.h"
63 #include "sync/internal_api/public/sync_encryption_handler.h"
64 #include "sync/internal_api/public/util/experiments.h"
65 #include "sync/internal_api/public/util/sync_string_conversions.h"
66 #include "sync/js/js_arg_list.h"
67 #include "sync/js/js_event_details.h"
68 #include "sync/util/cryptographer.h"
69 #include "ui/base/l10n/l10n_util.h"
71 using browser_sync::ChangeProcessor;
72 using browser_sync::DataTypeController;
73 using browser_sync::DataTypeManager;
74 using browser_sync::SyncBackendHost;
75 using syncer::ModelType;
76 using syncer::ModelTypeSet;
77 using syncer::JsBackend;
78 using syncer::JsController;
79 using syncer::JsEventDetails;
80 using syncer::JsEventHandler;
81 using syncer::ModelSafeRoutingInfo;
82 using syncer::SyncCredentials;
83 using syncer::SyncProtocolError;
84 using syncer::WeakHandle;
86 typedef GoogleServiceAuthError AuthError;
88 const char* ProfileSyncService::kSyncServerUrl =
89 "https://clients4.google.com/chrome-sync";
91 const char* ProfileSyncService::kDevServerUrl =
92 "https://clients4.google.com/chrome-sync/dev";
94 static const int kSyncClearDataTimeoutInSeconds = 60; // 1 minute.
96 static const char* kRelevantTokenServices[] = {
97 GaiaConstants::kSyncService
99 static const int kRelevantTokenServicesCount =
100 arraysize(kRelevantTokenServices);
102 static const char* kSyncUnrecoverableErrorHistogram =
103 "Sync.UnrecoverableErrors";
105 // Helper to check if the given token service is relevant for sync.
106 static bool IsTokenServiceRelevant(const std::string& service) {
107 for (int i = 0; i < kRelevantTokenServicesCount; ++i) {
108 if (service == kRelevantTokenServices[i])
109 return true;
111 return false;
114 bool ShouldShowActionOnUI(
115 const syncer::SyncProtocolError& error) {
116 return (error.action != syncer::UNKNOWN_ACTION &&
117 error.action != syncer::DISABLE_SYNC_ON_CLIENT);
120 ProfileSyncService::ProfileSyncService(ProfileSyncComponentsFactory* factory,
121 Profile* profile,
122 SigninManager* signin_manager,
123 StartBehavior start_behavior)
124 : last_auth_error_(AuthError::None()),
125 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
126 factory_(factory),
127 profile_(profile),
128 // |profile| may be NULL in unit tests.
129 sync_prefs_(profile_ ? profile_->GetPrefs() : NULL),
130 invalidator_storage_(profile_ ? profile_->GetPrefs(): NULL),
131 sync_service_url_(kDevServerUrl),
132 is_first_time_sync_configure_(false),
133 backend_initialized_(false),
134 is_auth_in_progress_(false),
135 signin_(signin_manager),
136 unrecoverable_error_reason_(ERROR_REASON_UNSET),
137 weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
138 expect_sync_configuration_aborted_(false),
139 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
140 encrypt_everything_(false),
141 encryption_pending_(false),
142 auto_start_enabled_(start_behavior == AUTO_START),
143 failed_datatypes_handler_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
144 configure_status_(DataTypeManager::UNKNOWN),
145 setup_in_progress_(false) {
146 #if defined(OS_ANDROID)
147 chrome::VersionInfo version_info;
148 if (version_info.IsOfficialBuild()) {
149 sync_service_url_ = GURL(kSyncServerUrl);
151 #else
152 // By default, dev, canary, and unbranded Chromium users will go to the
153 // development servers. Development servers have more features than standard
154 // sync servers. Users with officially-branded Chrome stable and beta builds
155 // will go to the standard sync servers.
157 // GetChannel hits the registry on Windows. See http://crbug.com/70380.
158 base::ThreadRestrictions::ScopedAllowIO allow_io;
159 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
160 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
161 channel == chrome::VersionInfo::CHANNEL_BETA) {
162 sync_service_url_ = GURL(kSyncServerUrl);
164 #endif
167 ProfileSyncService::~ProfileSyncService() {
168 sync_prefs_.RemoveSyncPrefObserver(this);
169 Shutdown();
172 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
173 // Exit if sync is disabled.
174 if (IsManaged() || sync_prefs_.IsStartSuppressed())
175 return false;
177 // Sync is logged in if there is a non-empty authenticated username.
178 return !signin_->GetAuthenticatedUsername().empty();
181 bool ProfileSyncService::IsSyncTokenAvailable() {
182 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
183 if (!token_service)
184 return false;
185 return token_service->HasTokenForService(GaiaConstants::kSyncService);
188 void ProfileSyncService::Initialize() {
189 InitSettings();
191 // We clear this here (vs Shutdown) because we want to remember that an error
192 // happened on shutdown so we can display details (message, location) about it
193 // in about:sync.
194 ClearStaleErrors();
196 sync_prefs_.AddSyncPrefObserver(this);
198 // For now, the only thing we can do through policy is to turn sync off.
199 if (IsManaged()) {
200 DisableForUser();
201 return;
204 RegisterAuthNotifications();
206 if (!HasSyncSetupCompleted() || signin_->GetAuthenticatedUsername().empty()) {
207 // Clean up in case of previous crash / setup abort / signout.
208 DisableForUser();
211 TryStart();
214 void ProfileSyncService::TryStart() {
215 if (!IsSyncEnabledAndLoggedIn())
216 return;
217 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
218 if (!token_service)
219 return;
220 // Don't start the backend if the token service hasn't finished loading tokens
221 // yet (if the backend is started before the sync token has been loaded,
222 // GetCredentials() will return bogus credentials). On auto_start platforms
223 // (like ChromeOS) we don't start sync until tokens are loaded, because the
224 // user can be "signed in" on those platforms long before the tokens get
225 // loaded, and we don't want to generate spurious auth errors.
226 if (IsSyncTokenAvailable() ||
227 (!auto_start_enabled_ && token_service->TokensLoadedFromDB())) {
228 if (HasSyncSetupCompleted() || auto_start_enabled_) {
229 // If sync setup has completed we always start the backend.
230 // If autostart is enabled, but we haven't completed sync setup, we try to
231 // start sync anyway, since it's possible we crashed/shutdown after
232 // logging in but before the backend finished initializing the last time.
233 // Note that if we haven't finished setting up sync, backend bring up will
234 // be done by the wizard.
235 StartUp();
240 void ProfileSyncService::StartSyncingWithServer() {
241 if (backend_.get())
242 backend_->StartSyncingWithServer();
245 void ProfileSyncService::RegisterAuthNotifications() {
246 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
247 registrar_.Add(this,
248 chrome::NOTIFICATION_TOKEN_AVAILABLE,
249 content::Source<TokenService>(token_service));
250 registrar_.Add(this,
251 chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
252 content::Source<TokenService>(token_service));
253 registrar_.Add(this,
254 chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
255 content::Source<TokenService>(token_service));
256 registrar_.Add(this,
257 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
258 content::Source<Profile>(profile_));
261 void ProfileSyncService::RegisterDataTypeController(
262 DataTypeController* data_type_controller) {
263 DCHECK_EQ(data_type_controllers_.count(data_type_controller->type()), 0U);
264 data_type_controllers_[data_type_controller->type()] =
265 data_type_controller;
268 browser_sync::SessionModelAssociator*
269 ProfileSyncService::GetSessionModelAssociator() {
270 if (data_type_controllers_.find(syncer::SESSIONS) ==
271 data_type_controllers_.end() ||
272 data_type_controllers_.find(syncer::SESSIONS)->second->state() !=
273 DataTypeController::RUNNING) {
274 return NULL;
276 return static_cast<browser_sync::SessionDataTypeController*>(
277 data_type_controllers_.find(
278 syncer::SESSIONS)->second.get())->GetModelAssociator();
281 void ProfileSyncService::GetDataTypeControllerStates(
282 browser_sync::DataTypeController::StateMap* state_map) const {
283 for (browser_sync::DataTypeController::TypeMap::const_iterator iter =
284 data_type_controllers_.begin(); iter != data_type_controllers_.end();
285 ++iter)
286 (*state_map)[iter->first] = iter->second.get()->state();
289 void ProfileSyncService::InitSettings() {
290 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
292 // Override the sync server URL from the command-line, if sync server
293 // command-line argument exists.
294 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
295 std::string value(command_line.GetSwitchValueASCII(
296 switches::kSyncServiceURL));
297 if (!value.empty()) {
298 GURL custom_sync_url(value);
299 if (custom_sync_url.is_valid()) {
300 sync_service_url_ = custom_sync_url;
301 } else {
302 LOG(WARNING) << "The following sync URL specified at the command-line "
303 << "is invalid: " << value;
309 SyncCredentials ProfileSyncService::GetCredentials() {
310 SyncCredentials credentials;
311 credentials.email = signin_->GetAuthenticatedUsername();
312 DCHECK(!credentials.email.empty());
313 TokenService* service = TokenServiceFactory::GetForProfile(profile_);
314 if (service->HasTokenForService(GaiaConstants::kSyncService)) {
315 credentials.sync_token = service->GetTokenForService(
316 GaiaConstants::kSyncService);
317 UMA_HISTOGRAM_BOOLEAN("Sync.CredentialsLost", false);
318 } else {
319 // We've lost our sync credentials (crbug.com/121755), so just make up some
320 // invalid credentials so the backend will generate an auth error.
321 UMA_HISTOGRAM_BOOLEAN("Sync.CredentialsLost", true);
322 credentials.sync_token = "credentials_lost";
324 return credentials;
327 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
328 if (!backend_.get()) {
329 NOTREACHED();
330 return;
333 SyncCredentials credentials = GetCredentials();
335 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
336 profile_->GetRequestContext());
338 if (delete_stale_data)
339 ClearStaleErrors();
341 backend_unrecoverable_error_handler_.reset(
342 new browser_sync::BackendUnrecoverableErrorHandler(
343 MakeWeakHandle(weak_factory_.GetWeakPtr())));
345 backend_->Initialize(
346 this,
347 MakeWeakHandle(sync_js_controller_.AsWeakPtr()),
348 sync_service_url_,
349 credentials,
350 delete_stale_data,
351 &sync_manager_factory_,
352 backend_unrecoverable_error_handler_.get(),
353 &browser_sync::ChromeReportUnrecoverableError);
356 void ProfileSyncService::CreateBackend() {
357 backend_.reset(
358 new SyncBackendHost(profile_->GetDebugName(),
359 profile_, sync_prefs_.AsWeakPtr(),
360 invalidator_storage_.AsWeakPtr()));
363 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
364 if (encryption_pending())
365 return true;
366 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
367 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
368 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
369 return !Intersection(preferred_types, encrypted_types).Empty();
372 void ProfileSyncService::OnSyncConfigureDone(
373 DataTypeManager::ConfigureResult result) {
374 if (failed_datatypes_handler_.UpdateFailedDatatypes(result.failed_data_types,
375 FailedDatatypesHandler::STARTUP)) {
376 ReconfigureDatatypeManager();
380 void ProfileSyncService::OnSyncConfigureRetry() {
381 // In platforms with auto start we would just wait for the
382 // configure to finish. In other platforms we would throw
383 // an unrecoverable error. The reason we do this is so that
384 // the login dialog would show an error and the user would have
385 // to relogin.
386 // Also if backend has been initialized(the user is authenticated
387 // and nigori is downloaded) we would simply wait rather than going into
388 // unrecoverable error, even if the platform has auto start disabled.
389 // Note: In those scenarios the UI does not wait for the configuration
390 // to finish.
391 if (!auto_start_enabled_ && !backend_initialized_) {
392 OnInternalUnrecoverableError(FROM_HERE,
393 "Configure failed to download.",
394 true,
395 ERROR_REASON_CONFIGURATION_RETRY);
398 NotifyObservers();
402 void ProfileSyncService::StartUp() {
403 // Don't start up multiple times.
404 if (backend_.get()) {
405 DVLOG(1) << "Skipping bringing up backend host.";
406 return;
409 DCHECK(IsSyncEnabledAndLoggedIn());
411 last_synced_time_ = sync_prefs_.GetLastSyncedTime();
412 start_up_time_ = base::Time::Now();
414 #if defined(OS_CHROMEOS)
415 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
416 if (bootstrap_token.empty()) {
417 sync_prefs_.SetEncryptionBootstrapToken(
418 sync_prefs_.GetSpareBootstrapToken());
420 #endif
421 CreateBackend();
423 // Initialize the backend. Every time we start up a new SyncBackendHost,
424 // we'll want to start from a fresh SyncDB, so delete any old one that might
425 // be there.
426 InitializeBackend(!HasSyncSetupCompleted());
428 // |backend_| may end up being NULL here in tests (in synchronous
429 // initialization mode).
431 // TODO(akalin): Fix this horribly non-intuitive behavior (see
432 // http://crbug.com/140354).
433 if (backend_.get()) {
434 backend_->UpdateRegisteredInvalidationIds(
435 invalidator_registrar_.GetAllRegisteredIds());
438 if (!sync_global_error_.get()) {
439 #if !defined(OS_ANDROID)
440 sync_global_error_.reset(new SyncGlobalError(this, signin()));
441 #endif
442 GlobalErrorServiceFactory::GetForProfile(profile_)->AddGlobalError(
443 sync_global_error_.get());
444 AddObserver(sync_global_error_.get());
448 void ProfileSyncService::RegisterInvalidationHandler(
449 syncer::InvalidationHandler* handler) {
450 invalidator_registrar_.RegisterHandler(handler);
453 void ProfileSyncService::UpdateRegisteredInvalidationIds(
454 syncer::InvalidationHandler* handler,
455 const syncer::ObjectIdSet& ids) {
456 invalidator_registrar_.UpdateRegisteredIds(handler, ids);
458 // If |backend_| is NULL, its registered IDs will be updated when
459 // it's created and initialized.
460 if (backend_.get()) {
461 backend_->UpdateRegisteredInvalidationIds(
462 invalidator_registrar_.GetAllRegisteredIds());
466 void ProfileSyncService::UnregisterInvalidationHandler(
467 syncer::InvalidationHandler* handler) {
468 invalidator_registrar_.UnregisterHandler(handler);
471 syncer::InvalidatorState ProfileSyncService::GetInvalidatorState() const {
472 return invalidator_registrar_.GetInvalidatorState();
475 void ProfileSyncService::Shutdown() {
476 ShutdownImpl(false);
479 void ProfileSyncService::ShutdownImpl(bool sync_disabled) {
480 // First, we spin down the backend and wait for it to stop syncing completely
481 // before we Stop the data type manager. This is to avoid a late sync cycle
482 // applying changes to the sync db that wouldn't get applied via
483 // ChangeProcessors, leading to back-from-the-dead bugs.
484 base::Time shutdown_start_time = base::Time::Now();
485 if (backend_.get()) {
486 backend_->StopSyncingForShutdown();
489 // Stop all data type controllers, if needed. Note that until Stop
490 // completes, it is possible in theory to have a ChangeProcessor apply a
491 // change from a native model. In that case, it will get applied to the sync
492 // database (which doesn't get destroyed until we destroy the backend below)
493 // as an unsynced change. That will be persisted, and committed on restart.
494 if (data_type_manager_.get()) {
495 if (data_type_manager_->state() != DataTypeManager::STOPPED) {
496 // When aborting as part of shutdown, we should expect an aborted sync
497 // configure result, else we'll dcheck when we try to read the sync error.
498 expect_sync_configuration_aborted_ = true;
499 data_type_manager_->Stop();
501 data_type_manager_.reset();
504 // Shutdown the migrator before the backend to ensure it doesn't pull a null
505 // snapshot.
506 migrator_.reset();
507 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
509 // Move aside the backend so nobody else tries to use it while we are
510 // shutting it down.
511 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
512 if (doomed_backend.get()) {
513 doomed_backend->Shutdown(sync_disabled);
515 doomed_backend.reset();
517 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
518 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
520 weak_factory_.InvalidateWeakPtrs();
522 // Clear various flags.
523 expect_sync_configuration_aborted_ = false;
524 is_auth_in_progress_ = false;
525 backend_initialized_ = false;
526 cached_passphrase_.clear();
527 encryption_pending_ = false;
528 encrypt_everything_ = false;
529 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
530 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
531 last_auth_error_ = AuthError::None();
533 if (sync_global_error_.get()) {
534 GlobalErrorServiceFactory::GetForProfile(profile_)->RemoveGlobalError(
535 sync_global_error_.get());
536 RemoveObserver(sync_global_error_.get());
537 sync_global_error_.reset(NULL);
541 void ProfileSyncService::DisableForUser() {
542 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
543 // PSS clients don't think we're set up while we're shutting down.
544 sync_prefs_.ClearPreferences();
545 invalidator_storage_.Clear();
546 ClearUnrecoverableError();
547 ShutdownImpl(true);
549 // TODO(atwilson): Don't call SignOut() on *any* platform - move this into
550 // the UI layer if needed (sync activity should never result in the user
551 // being logged out of all chrome services).
552 if (!auto_start_enabled_ && !signin_->GetAuthenticatedUsername().empty())
553 signin_->SignOut();
555 NotifyObservers();
558 bool ProfileSyncService::HasSyncSetupCompleted() const {
559 return sync_prefs_.HasSyncSetupCompleted();
562 void ProfileSyncService::SetSyncSetupCompleted() {
563 sync_prefs_.SetSyncSetupCompleted();
566 void ProfileSyncService::UpdateLastSyncedTime() {
567 last_synced_time_ = base::Time::Now();
568 sync_prefs_.SetLastSyncedTime(last_synced_time_);
571 void ProfileSyncService::NotifyObservers() {
572 FOR_EACH_OBSERVER(Observer, observers_, OnStateChanged());
573 // TODO(akalin): Make an Observer subclass that listens and does the
574 // event routing.
575 sync_js_controller_.HandleJsEvent(
576 "onServiceStateChanged", JsEventDetails());
579 void ProfileSyncService::ClearStaleErrors() {
580 ClearUnrecoverableError();
581 last_actionable_error_ = SyncProtocolError();
584 void ProfileSyncService::ClearUnrecoverableError() {
585 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
586 unrecoverable_error_message_.clear();
587 unrecoverable_error_location_ = tracked_objects::Location();
590 // static
591 std::string ProfileSyncService::GetExperimentNameForDataType(
592 syncer::ModelType data_type) {
593 switch (data_type) {
594 case syncer::SESSIONS:
595 return "sync-tabs";
596 default:
597 break;
599 NOTREACHED();
600 return "";
603 void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) {
604 if (data_type_controllers_.count(data_type) > 0)
605 return;
606 NOTREACHED();
609 // An invariant has been violated. Transition to an error state where we try
610 // to do as little work as possible, to avoid further corruption or crashes.
611 void ProfileSyncService::OnUnrecoverableError(
612 const tracked_objects::Location& from_here,
613 const std::string& message) {
614 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
615 // interface are assumed to originate within the syncer.
616 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
617 OnUnrecoverableErrorImpl(from_here, message, true);
620 void ProfileSyncService::OnUnrecoverableErrorImpl(
621 const tracked_objects::Location& from_here,
622 const std::string& message,
623 bool delete_sync_database) {
624 DCHECK(HasUnrecoverableError());
625 unrecoverable_error_message_ = message;
626 unrecoverable_error_location_ = from_here;
628 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
629 unrecoverable_error_reason_,
630 ERROR_REASON_LIMIT);
631 NotifyObservers();
632 std::string location;
633 from_here.Write(true, true, &location);
634 LOG(ERROR)
635 << "Unrecoverable error detected at " << location
636 << " -- ProfileSyncService unusable: " << message;
638 // Shut all data types down.
639 MessageLoop::current()->PostTask(FROM_HERE,
640 base::Bind(&ProfileSyncService::ShutdownImpl, weak_factory_.GetWeakPtr(),
641 delete_sync_database));
644 void ProfileSyncService::DisableBrokenDatatype(
645 syncer::ModelType type,
646 const tracked_objects::Location& from_here,
647 std::string message) {
648 // First deactivate the type so that no further server changes are
649 // passed onto the change processor.
650 DeactivateDataType(type);
652 syncer::SyncError error(from_here, message, type);
654 std::list<syncer::SyncError> errors;
655 errors.push_back(error);
657 // Update this before posting a task. So if a configure happens before
658 // the task that we are going to post, this type would still be disabled.
659 failed_datatypes_handler_.UpdateFailedDatatypes(errors,
660 FailedDatatypesHandler::RUNTIME);
662 MessageLoop::current()->PostTask(FROM_HERE,
663 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager,
664 weak_factory_.GetWeakPtr()));
667 void ProfileSyncService::OnInvalidatorStateChange(
668 syncer::InvalidatorState state) {
669 invalidator_registrar_.UpdateInvalidatorState(state);
672 void ProfileSyncService::OnIncomingInvalidation(
673 const syncer::ObjectIdStateMap& id_state_map,
674 syncer::IncomingInvalidationSource source) {
675 invalidator_registrar_.DispatchInvalidationsToHandlers(id_state_map, source);
678 void ProfileSyncService::OnBackendInitialized(
679 const syncer::WeakHandle<syncer::JsBackend>& js_backend, bool success) {
680 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
682 if (is_first_time_sync_configure_) {
683 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
684 } else {
685 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
688 if (!start_up_time_.is_null()) {
689 base::Time on_backend_initialized_time = base::Time::Now();
690 base::TimeDelta delta = on_backend_initialized_time - start_up_time_;
691 if (is_first_time_sync_configure_) {
692 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
693 } else {
694 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
696 start_up_time_ = base::Time();
699 if (!success) {
700 // Something went unexpectedly wrong. Play it safe: stop syncing at once
701 // and surface error UI to alert the user sync has stopped.
702 // Keep the directory around for now so that on restart we will retry
703 // again and potentially succeed in presence of transient file IO failures
704 // or permissions issues, etc.
706 // TODO(rlarocque): Consider making this UnrecoverableError less special.
707 // Unlike every other UnrecoverableError, it does not delete our sync data.
708 // This exception made sense at the time it was implemented, but our new
709 // directory corruption recovery mechanism makes it obsolete. By the time
710 // we get here, we will have already tried and failed to delete the
711 // directory. It would be no big deal if we tried to delete it again.
712 OnInternalUnrecoverableError(FROM_HERE,
713 "BackendInitialize failure",
714 false,
715 ERROR_REASON_BACKEND_INIT_FAILURE);
716 return;
719 backend_initialized_ = true;
721 sync_js_controller_.AttachJsBackend(js_backend);
723 // If we have a cached passphrase use it to decrypt/encrypt data now that the
724 // backend is initialized. We want to call this before notifying observers in
725 // case this operation affects the "passphrase required" status.
726 ConsumeCachedPassphraseIfPossible();
728 // The very first time the backend initializes is effectively the first time
729 // we can say we successfully "synced". last_synced_time_ will only be null
730 // in this case, because the pref wasn't restored on StartUp.
731 if (last_synced_time_.is_null()) {
732 UpdateLastSyncedTime();
734 NotifyObservers();
736 if (auto_start_enabled_ && !FirstSetupInProgress()) {
737 // Backend is initialized but we're not in sync setup, so this must be an
738 // autostart - mark our sync setup as completed and we'll start syncing
739 // below.
740 SetSyncSetupCompleted();
741 NotifyObservers();
744 if (HasSyncSetupCompleted()) {
745 ConfigureDataTypeManager();
746 } else {
747 DCHECK(FirstSetupInProgress());
751 void ProfileSyncService::OnSyncCycleCompleted() {
752 UpdateLastSyncedTime();
753 if (GetSessionModelAssociator()) {
754 // Trigger garbage collection of old sessions now that we've downloaded
755 // any new session data. TODO(zea): Have this be a notification the session
756 // model associator listens too. Also consider somehow plumbing the current
757 // server time as last reported by CheckServerReachable, so we don't have to
758 // rely on the local clock, which may be off significantly.
759 MessageLoop::current()->PostTask(FROM_HERE,
760 base::Bind(&browser_sync::SessionModelAssociator::DeleteStaleSessions,
761 GetSessionModelAssociator()->AsWeakPtr()));
763 DVLOG(2) << "Notifying observers sync cycle completed";
764 NotifyObservers();
767 void ProfileSyncService::OnExperimentsChanged(
768 const syncer::Experiments& experiments) {
769 if (current_experiments.Matches(experiments))
770 return;
772 // If this is a first time sync for a client, this will be called before
773 // OnBackendInitialized() to ensure the new datatypes are available at sync
774 // setup. As a result, the migrator won't exist yet. This is fine because for
775 // first time sync cases we're only concerned with making the datatype
776 // available.
777 if (migrator_.get() &&
778 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
779 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
780 return;
783 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
784 syncer::ModelTypeSet to_add;
785 const syncer::ModelTypeSet to_register =
786 Difference(to_add, registered_types);
787 DVLOG(2) << "OnExperimentsChanged called with types: "
788 << syncer::ModelTypeSetToString(to_add);
789 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register);
791 for (syncer::ModelTypeSet::Iterator it = to_register.First();
792 it.Good(); it.Inc()) {
793 // Received notice to enable experimental type. Check if the type is
794 // registered, and if not register a new datatype controller.
795 RegisterNewDataType(it.Get());
796 // Enable the about:flags switch for the experimental type so we don't have
797 // to always perform this reconfiguration. Once we set this, the type will
798 // remain registered on restart, so we will no longer go down this code
799 // path.
800 std::string experiment_name = GetExperimentNameForDataType(it.Get());
801 if (experiment_name.empty())
802 continue;
803 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
804 experiment_name,
805 true);
808 // Check if the user has "Keep Everything Synced" enabled. If so, we want
809 // to turn on all experimental types if they're not already on. Otherwise we
810 // leave them off.
811 // Note: if any types are already registered, we don't turn them on. This
812 // covers the case where we're already in the process of reconfiguring
813 // to turn an experimental type on.
814 if (sync_prefs_.HasKeepEverythingSynced()) {
815 // Mark all data types as preferred.
816 sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
818 // Only automatically turn on types if we have already finished set up.
819 // Otherwise, just leave the experimental types on by default.
820 if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_.get()) {
821 DVLOG(1) << "Dynamically enabling new datatypes: "
822 << syncer::ModelTypeSetToString(to_register);
823 OnMigrationNeededForTypes(to_register);
827 // Now enable any non-datatype features.
828 if (experiments.sync_tab_favicons) {
829 DVLOG(1) << "Enabling syncing of tab favicons.";
830 about_flags::SetExperimentEnabled(g_browser_process->local_state(),
831 "sync-tab-favicons",
832 true);
833 #if defined(OS_ANDROID)
834 // Android does not support about:flags and experiments, so we need to force
835 // setting the experiments as command line switches.
836 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kSyncTabFavicons);
837 #endif
840 current_experiments = experiments;
843 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
844 is_auth_in_progress_ = false;
845 last_auth_error_ = error;
847 // Fan the notification out to interested UI-thread components.
848 NotifyObservers();
851 namespace {
853 AuthError ConnectionStatusToAuthError(
854 syncer::ConnectionStatus status) {
855 switch (status) {
856 case syncer::CONNECTION_OK:
857 return AuthError::None();
858 break;
859 case syncer::CONNECTION_AUTH_ERROR:
860 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
861 break;
862 case syncer::CONNECTION_SERVER_ERROR:
863 return AuthError(AuthError::CONNECTION_FAILED);
864 break;
865 default:
866 NOTREACHED();
867 return AuthError(AuthError::CONNECTION_FAILED);
871 } // namespace
873 void ProfileSyncService::OnConnectionStatusChange(
874 syncer::ConnectionStatus status) {
875 UpdateAuthErrorState(ConnectionStatusToAuthError(status));
878 void ProfileSyncService::OnStopSyncingPermanently() {
879 UpdateAuthErrorState(AuthError(AuthError::SERVICE_UNAVAILABLE));
880 sync_prefs_.SetStartSuppressed(true);
881 DisableForUser();
884 void ProfileSyncService::OnPassphraseRequired(
885 syncer::PassphraseRequiredReason reason,
886 const sync_pb::EncryptedData& pending_keys) {
887 DCHECK(backend_.get());
888 DCHECK(backend_->IsNigoriEnabled());
890 // TODO(lipalani) : add this check to other locations as well.
891 if (HasUnrecoverableError()) {
892 // When unrecoverable error is detected we post a task to shutdown the
893 // backend. The task might not have executed yet.
894 return;
897 DVLOG(1) << "Passphrase required with reason: "
898 << syncer::PassphraseRequiredReasonToString(reason);
899 passphrase_required_reason_ = reason;
901 // Notify observers that the passphrase status may have changed.
902 NotifyObservers();
905 void ProfileSyncService::OnPassphraseAccepted() {
906 DVLOG(1) << "Received OnPassphraseAccepted.";
907 // If we are not using an explicit passphrase, and we have a cache of the gaia
908 // password, use it for encryption at this point.
909 DCHECK(cached_passphrase_.empty()) <<
910 "Passphrase no longer required but there is still a cached passphrase";
912 // Reset passphrase_required_reason_ since we know we no longer require the
913 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
914 // because that can be called by OnPassphraseRequired() if no encrypted data
915 // types are enabled, and we don't want to clobber the true passphrase error.
916 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
918 // Make sure the data types that depend on the passphrase are started at
919 // this time.
920 const syncer::ModelTypeSet types = GetPreferredDataTypes();
922 if (data_type_manager_.get()) {
923 // Unblock the data type manager if necessary.
924 data_type_manager_->Configure(types,
925 syncer::CONFIGURE_REASON_RECONFIGURATION);
928 NotifyObservers();
931 void ProfileSyncService::OnEncryptedTypesChanged(
932 syncer::ModelTypeSet encrypted_types,
933 bool encrypt_everything) {
934 encrypted_types_ = encrypted_types;
935 encrypt_everything_ = encrypt_everything;
936 DVLOG(1) << "Encrypted types changed to "
937 << syncer::ModelTypeSetToString(encrypted_types_)
938 << " (encrypt everything is set to "
939 << (encrypt_everything_ ? "true" : "false") << ")";
940 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
943 void ProfileSyncService::OnEncryptionComplete() {
944 DVLOG(1) << "Encryption complete";
945 if (encryption_pending_ && encrypt_everything_) {
946 encryption_pending_ = false;
947 // This is to nudge the integration tests when encryption is
948 // finished.
949 NotifyObservers();
953 void ProfileSyncService::OnMigrationNeededForTypes(
954 syncer::ModelTypeSet types) {
955 DCHECK(backend_initialized_);
956 DCHECK(data_type_manager_.get());
958 // Migrator must be valid, because we don't sync until it is created and this
959 // callback originates from a sync cycle.
960 migrator_->MigrateTypes(types);
963 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
964 last_actionable_error_ = error;
965 DCHECK_NE(last_actionable_error_.action,
966 syncer::UNKNOWN_ACTION);
967 switch (error.action) {
968 case syncer::UPGRADE_CLIENT:
969 case syncer::CLEAR_USER_DATA_AND_RESYNC:
970 case syncer::ENABLE_SYNC_ON_ACCOUNT:
971 case syncer::STOP_AND_RESTART_SYNC:
972 // TODO(lipalani) : if setup in progress we want to display these
973 // actions in the popup. The current experience might not be optimal for
974 // the user. We just dismiss the dialog.
975 if (setup_in_progress_) {
976 OnStopSyncingPermanently();
977 expect_sync_configuration_aborted_ = true;
979 // Trigger an unrecoverable error to stop syncing.
980 OnInternalUnrecoverableError(FROM_HERE,
981 last_actionable_error_.error_description,
982 true,
983 ERROR_REASON_ACTIONABLE_ERROR);
984 break;
985 case syncer::DISABLE_SYNC_ON_CLIENT:
986 OnStopSyncingPermanently();
987 break;
988 default:
989 NOTREACHED();
991 NotifyObservers();
994 void ProfileSyncService::OnConfigureBlocked() {
995 NotifyObservers();
998 void ProfileSyncService::OnConfigureDone(
999 const browser_sync::DataTypeManager::ConfigureResult& result) {
1000 // We should have cleared our cached passphrase before we get here (in
1001 // OnBackendInitialized()).
1002 DCHECK(cached_passphrase_.empty());
1004 if (!sync_configure_start_time_.is_null()) {
1005 if (result.status == DataTypeManager::OK ||
1006 result.status == DataTypeManager::PARTIAL_SUCCESS) {
1007 base::Time sync_configure_stop_time = base::Time::Now();
1008 base::TimeDelta delta = sync_configure_stop_time -
1009 sync_configure_start_time_;
1010 if (is_first_time_sync_configure_) {
1011 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1012 } else {
1013 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1014 delta);
1017 sync_configure_start_time_ = base::Time();
1020 // Notify listeners that configuration is done.
1021 content::NotificationService::current()->Notify(
1022 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1023 content::Source<ProfileSyncService>(this),
1024 content::NotificationService::NoDetails());
1026 configure_status_ = result.status;
1027 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1028 // The possible status values:
1029 // ABORT - Configuration was aborted. This is not an error, if
1030 // initiated by user.
1031 // OK - Everything succeeded.
1032 // PARTIAL_SUCCESS - Some datatypes failed to start.
1033 // Everything else is an UnrecoverableError. So treat it as such.
1035 // First handle the abort case.
1036 if (configure_status_ == DataTypeManager::ABORTED &&
1037 expect_sync_configuration_aborted_) {
1038 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1039 expect_sync_configuration_aborted_ = false;
1040 return;
1043 // Handle unrecoverable error.
1044 if (configure_status_ != DataTypeManager::OK &&
1045 configure_status_ != DataTypeManager::PARTIAL_SUCCESS) {
1046 // Something catastrophic had happened. We should only have one
1047 // error representing it.
1048 DCHECK_EQ(result.failed_data_types.size(),
1049 static_cast<unsigned int>(1));
1050 syncer::SyncError error = result.failed_data_types.front();
1051 DCHECK(error.IsSet());
1052 std::string message =
1053 "Sync configuration failed with status " +
1054 DataTypeManager::ConfigureStatusToString(configure_status_) +
1055 " during " + syncer::ModelTypeToString(error.type()) +
1056 ": " + error.message();
1057 LOG(ERROR) << "ProfileSyncService error: "
1058 << message;
1059 OnInternalUnrecoverableError(error.location(),
1060 message,
1061 true,
1062 ERROR_REASON_CONFIGURATION_FAILURE);
1063 return;
1066 // Now handle partial success and full success.
1067 MessageLoop::current()->PostTask(FROM_HERE,
1068 base::Bind(&ProfileSyncService::OnSyncConfigureDone,
1069 weak_factory_.GetWeakPtr(), result));
1071 // We should never get in a state where we have no encrypted datatypes
1072 // enabled, and yet we still think we require a passphrase for decryption.
1073 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1074 !IsEncryptedDatatypeEnabled()));
1076 // This must be done before we start syncing with the server to avoid
1077 // sending unencrypted data up on a first time sync.
1078 if (encryption_pending_)
1079 backend_->EnableEncryptEverything();
1080 NotifyObservers();
1082 if (migrator_.get() &&
1083 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1084 // Migration in progress. Let the migrator know we just finished
1085 // configuring something. It will be up to the migrator to call
1086 // StartSyncingWithServer() if migration is now finished.
1087 migrator_->OnConfigureDone(result);
1088 } else {
1089 StartSyncingWithServer();
1093 void ProfileSyncService::OnConfigureRetry() {
1094 // We should have cleared our cached passphrase before we get here (in
1095 // OnBackendInitialized()).
1096 DCHECK(cached_passphrase_.empty());
1098 OnSyncConfigureRetry();
1101 void ProfileSyncService::OnConfigureStart() {
1102 sync_configure_start_time_ = base::Time::Now();
1103 content::NotificationService::current()->Notify(
1104 chrome::NOTIFICATION_SYNC_CONFIGURE_START,
1105 content::Source<ProfileSyncService>(this),
1106 content::NotificationService::NoDetails());
1107 NotifyObservers();
1110 std::string ProfileSyncService::QuerySyncStatusSummary() {
1111 if (HasUnrecoverableError()) {
1112 return "Unrecoverable error detected";
1113 } else if (!backend_.get()) {
1114 return "Syncing not enabled";
1115 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1116 return "First time sync setup incomplete";
1117 } else if (backend_.get() && HasSyncSetupCompleted() &&
1118 data_type_manager_.get() &&
1119 data_type_manager_->state() != DataTypeManager::CONFIGURED) {
1120 return "Datatypes not fully initialized";
1121 } else if (ShouldPushChanges()) {
1122 return "Sync service initialized";
1123 } else {
1124 return "Status unknown: Internal error?";
1128 bool ProfileSyncService::QueryDetailedSyncStatus(
1129 SyncBackendHost::Status* result) {
1130 if (backend_.get() && backend_initialized_) {
1131 *result = backend_->GetDetailedStatus();
1132 return true;
1133 } else {
1134 SyncBackendHost::Status status;
1135 status.sync_protocol_error = last_actionable_error_;
1136 *result = status;
1137 return false;
1141 const AuthError& ProfileSyncService::GetAuthError() const {
1142 return last_auth_error_;
1145 bool ProfileSyncService::FirstSetupInProgress() const {
1146 return !HasSyncSetupCompleted() && setup_in_progress_;
1149 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1150 bool was_in_progress = setup_in_progress_;
1151 setup_in_progress_ = setup_in_progress;
1152 if (!setup_in_progress && was_in_progress) {
1153 if (sync_initialized()) {
1154 ReconfigureDatatypeManager();
1159 bool ProfileSyncService::sync_initialized() const {
1160 return backend_initialized_;
1163 bool ProfileSyncService::waiting_for_auth() const {
1164 return is_auth_in_progress_;
1167 bool ProfileSyncService::HasUnrecoverableError() const {
1168 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1171 bool ProfileSyncService::IsPassphraseRequired() const {
1172 return passphrase_required_reason_ !=
1173 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1176 // TODO(zea): Rename this IsPassphraseNeededFromUI and ensure it's used
1177 // appropriately (see http://crbug.com/91379).
1178 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1179 // If there is an encrypted datatype enabled and we don't have the proper
1180 // passphrase, we must prompt the user for a passphrase. The only way for the
1181 // user to avoid entering their passphrase is to disable the encrypted types.
1182 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1185 string16 ProfileSyncService::GetLastSyncedTimeString() const {
1186 if (last_synced_time_.is_null())
1187 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1189 base::TimeDelta last_synced = base::Time::Now() - last_synced_time_;
1191 if (last_synced < base::TimeDelta::FromMinutes(1))
1192 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1194 return TimeFormat::TimeElapsed(last_synced);
1197 void ProfileSyncService::UpdateSelectedTypesHistogram(
1198 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1199 if (!HasSyncSetupCompleted() ||
1200 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1201 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1204 // Only log the data types that are shown in the sync settings ui.
1205 const syncer::ModelType model_types[] = {
1206 syncer::APPS,
1207 syncer::AUTOFILL,
1208 syncer::BOOKMARKS,
1209 syncer::EXTENSIONS,
1210 syncer::PASSWORDS,
1211 syncer::PREFERENCES,
1212 syncer::SESSIONS,
1213 syncer::THEMES,
1214 syncer::TYPED_URLS
1217 const browser_sync::user_selectable_type::UserSelectableSyncType
1218 user_selectable_types[] = {
1219 browser_sync::user_selectable_type::APPS,
1220 browser_sync::user_selectable_type::AUTOFILL,
1221 browser_sync::user_selectable_type::BOOKMARKS,
1222 browser_sync::user_selectable_type::EXTENSIONS,
1223 browser_sync::user_selectable_type::PASSWORDS,
1224 browser_sync::user_selectable_type::PREFERENCES,
1225 browser_sync::user_selectable_type::SESSIONS,
1226 browser_sync::user_selectable_type::THEMES,
1227 browser_sync::user_selectable_type::TYPED_URLS
1230 COMPILE_ASSERT(17 == syncer::MODEL_TYPE_COUNT, UpdateCustomConfigHistogram);
1231 COMPILE_ASSERT(arraysize(model_types) ==
1232 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT,
1233 UpdateCustomConfigHistogram);
1234 COMPILE_ASSERT(arraysize(model_types) == arraysize(user_selectable_types),
1235 UpdateCustomConfigHistogram);
1237 if (!sync_everything) {
1238 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1239 for (size_t i = 0; i < arraysize(model_types); ++i) {
1240 const syncer::ModelType type = model_types[i];
1241 if (chosen_types.Has(type) &&
1242 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1243 // Selected type has changed - log it.
1244 UMA_HISTOGRAM_ENUMERATION(
1245 "Sync.CustomSync",
1246 user_selectable_types[i],
1247 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1253 #if defined(OS_CHROMEOS)
1254 void ProfileSyncService::RefreshSpareBootstrapToken(
1255 const std::string& passphrase) {
1256 browser_sync::ChromeEncryptor encryptor;
1257 syncer::Cryptographer temp_cryptographer(&encryptor);
1258 // The first 2 params (hostname and username) doesn't have any effect here.
1259 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1261 std::string bootstrap_token;
1262 if (!temp_cryptographer.AddKey(key_params)) {
1263 NOTREACHED() << "Failed to add key to cryptographer.";
1265 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1266 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1268 #endif
1270 void ProfileSyncService::OnUserChoseDatatypes(bool sync_everything,
1271 syncer::ModelTypeSet chosen_types) {
1272 if (!backend_.get() && !HasUnrecoverableError()) {
1273 NOTREACHED();
1274 return;
1277 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1278 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1280 failed_datatypes_handler_.OnUserChoseDatatypes();
1281 ChangePreferredDataTypes(chosen_types);
1282 AcknowledgeSyncedTypes();
1283 NotifyObservers();
1286 void ProfileSyncService::ChangePreferredDataTypes(
1287 syncer::ModelTypeSet preferred_types) {
1289 DVLOG(1) << "ChangePreferredDataTypes invoked";
1290 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1291 const syncer::ModelTypeSet registered_preferred_types =
1292 Intersection(registered_types, preferred_types);
1293 sync_prefs_.SetPreferredDataTypes(registered_types,
1294 registered_preferred_types);
1296 // Now reconfigure the DTM.
1297 ReconfigureDatatypeManager();
1300 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1301 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1302 const syncer::ModelTypeSet preferred_types =
1303 sync_prefs_.GetPreferredDataTypes(registered_types);
1304 const syncer::ModelTypeSet failed_types =
1305 failed_datatypes_handler_.GetFailedTypes();
1306 return Difference(preferred_types, failed_types);
1309 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1310 syncer::ModelTypeSet registered_types;
1311 // The data_type_controllers_ are determined by command-line flags; that's
1312 // effectively what controls the values returned here.
1313 for (DataTypeController::TypeMap::const_iterator it =
1314 data_type_controllers_.begin();
1315 it != data_type_controllers_.end(); ++it) {
1316 registered_types.Put(it->first);
1318 return registered_types;
1321 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1322 return backend_->IsUsingExplicitPassphrase();
1325 bool ProfileSyncService::IsCryptographerReady(
1326 const syncer::BaseTransaction* trans) const {
1327 return backend_.get() && backend_->IsCryptographerReady(trans);
1330 SyncBackendHost* ProfileSyncService::GetBackendForTest() {
1331 // We don't check |backend_initialized_|; we assume the test class
1332 // knows what it's doing.
1333 return backend_.get();
1336 void ProfileSyncService::ConfigureDataTypeManager() {
1337 // Don't configure datatypes if the setup UI is still on the screen - this
1338 // is to help multi-screen setting UIs (like iOS) where they don't want to
1339 // start syncing data until the user is done configuring encryption options,
1340 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1341 // SetSetupInProgress(false).
1342 if (setup_in_progress_)
1343 return;
1345 bool restart = false;
1346 if (!data_type_manager_.get()) {
1347 restart = true;
1348 data_type_manager_.reset(
1349 factory_->CreateDataTypeManager(backend_.get(),
1350 &data_type_controllers_,
1351 this));
1353 // We create the migrator at the same time.
1354 migrator_.reset(
1355 new browser_sync::BackendMigrator(
1356 profile_->GetDebugName(), GetUserShare(),
1357 this, data_type_manager_.get(),
1358 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1359 base::Unretained(this))));
1362 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1363 if (IsPassphraseRequiredForDecryption()) {
1364 // We need a passphrase still. We don't bother to attempt to configure
1365 // until we receive an OnPassphraseAccepted (which triggers a configure).
1366 DVLOG(1) << "ProfileSyncService::ConfigureDataTypeManager bailing out "
1367 << "because a passphrase required";
1368 NotifyObservers();
1369 return;
1371 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1372 if (!HasSyncSetupCompleted()) {
1373 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1374 } else if (restart) {
1375 // Datatype downloads on restart are generally due to newly supported
1376 // datatypes (although it's also possible we're picking up where a failed
1377 // previous configuration left off).
1378 // TODO(sync): consider detecting configuration recovery and setting
1379 // the reason here appropriately.
1380 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1381 } else {
1382 // The user initiated a reconfiguration (either to add or remove types).
1383 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1386 data_type_manager_->Configure(types, reason);
1389 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1390 if (backend_.get() && backend_initialized_) {
1391 return backend_->GetUserShare();
1393 NOTREACHED();
1394 return NULL;
1397 syncer::sessions::SyncSessionSnapshot
1398 ProfileSyncService::GetLastSessionSnapshot() const {
1399 if (backend_.get() && backend_initialized_) {
1400 return backend_->GetLastSessionSnapshot();
1402 NOTREACHED();
1403 return syncer::sessions::SyncSessionSnapshot();
1406 bool ProfileSyncService::HasUnsyncedItems() const {
1407 if (backend_.get() && backend_initialized_) {
1408 return backend_->HasUnsyncedItems();
1410 NOTREACHED();
1411 return false;
1414 browser_sync::BackendMigrator*
1415 ProfileSyncService::GetBackendMigratorForTest() {
1416 return migrator_.get();
1419 void ProfileSyncService::GetModelSafeRoutingInfo(
1420 syncer::ModelSafeRoutingInfo* out) const {
1421 if (backend_.get() && backend_initialized_) {
1422 backend_->GetModelSafeRoutingInfo(out);
1423 } else {
1424 NOTREACHED();
1428 Value* ProfileSyncService::GetTypeStatusMap() const {
1429 ListValue* result = new ListValue();
1431 if (!backend_.get() || !backend_initialized_) {
1432 return result;
1435 std::vector<syncer::SyncError> errors =
1436 failed_datatypes_handler_.GetAllErrors();
1437 std::map<ModelType, syncer::SyncError> error_map;
1438 for (std::vector<syncer::SyncError>::iterator it = errors.begin();
1439 it != errors.end(); ++it) {
1440 error_map[it->type()] = *it;
1443 ModelTypeSet active_types;
1444 ModelTypeSet passive_types;
1445 ModelSafeRoutingInfo routing_info;
1446 backend_->GetModelSafeRoutingInfo(&routing_info);
1447 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1448 it != routing_info.end(); ++it) {
1449 if (it->second == syncer::GROUP_PASSIVE) {
1450 passive_types.Put(it->first);
1451 } else {
1452 active_types.Put(it->first);
1456 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
1457 ModelTypeSet &throttled_types(detailed_status.throttled_types);
1459 ModelTypeSet registered = GetRegisteredDataTypes();
1460 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
1461 ModelType type = it.Get();
1462 DictionaryValue* type_status = new DictionaryValue();
1464 result->Append(type_status);
1465 type_status->SetString("name", ModelTypeToString(type));
1467 if (error_map.find(type) != error_map.end()) {
1468 const syncer::SyncError &error = error_map.find(type)->second;
1469 DCHECK(error.IsSet());
1470 std::string error_text = "Error: " + error.location().ToString() +
1471 ", " + error.message();
1472 type_status->SetString("status", "error");
1473 type_status->SetString("value", error_text);
1474 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
1475 type_status->SetString("status", "warning");
1476 type_status->SetString("value", "Passive, Throttled");
1477 } else if (passive_types.Has(type)) {
1478 type_status->SetString("status", "warning");
1479 type_status->SetString("value", "Passive");
1480 } else if (throttled_types.Has(type)) {
1481 type_status->SetString("status", "warning");
1482 type_status->SetString("value", "Throttled");
1483 } else if (active_types.Has(type)) {
1484 type_status->SetString("status", "ok");
1485 type_status->SetString("value", "Active: " +
1486 ModelSafeGroupToString(routing_info[type]));
1487 } else {
1488 type_status->SetString("status", "warning");
1489 type_status->SetString("value", "Disabled by User");
1492 return result;
1495 void ProfileSyncService::ActivateDataType(
1496 syncer::ModelType type, syncer::ModelSafeGroup group,
1497 ChangeProcessor* change_processor) {
1498 if (!backend_.get()) {
1499 NOTREACHED();
1500 return;
1502 DCHECK(backend_initialized_);
1503 backend_->ActivateDataType(type, group, change_processor);
1506 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
1507 if (!backend_.get())
1508 return;
1509 backend_->DeactivateDataType(type);
1512 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
1513 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
1514 // If the backend isn't running yet, OnBackendInitialized() will call this
1515 // method again after the backend starts up.
1516 if (cached_passphrase_.empty() || !sync_initialized())
1517 return;
1519 // Backend is up and running, so we can consume the cached passphrase.
1520 std::string passphrase = cached_passphrase_;
1521 cached_passphrase_.clear();
1523 // If we need a passphrase to decrypt data, try the cached passphrase.
1524 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
1525 if (SetDecryptionPassphrase(passphrase)) {
1526 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
1527 return;
1531 // If we get here, we don't have pending keys (or at least, the passphrase
1532 // doesn't decrypt them) - just try to re-encrypt using the encryption
1533 // passphrase.
1534 if (!IsUsingSecondaryPassphrase())
1535 SetEncryptionPassphrase(passphrase, IMPLICIT);
1538 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
1539 PassphraseType type) {
1540 // This should only be called when the backend has been initialized.
1541 DCHECK(sync_initialized());
1542 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
1543 "Data is already encrypted using an explicit passphrase";
1544 DCHECK(!(type == EXPLICIT && IsPassphraseRequired())) <<
1545 "Cannot switch to an explicit passphrase if a passphrase is required";
1547 if (type == EXPLICIT)
1548 UMA_HISTOGRAM_BOOLEAN("Sync.CustomPassphrase", true);
1550 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
1551 << " passphrase for encryption.";
1552 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
1553 // REASON_ENCRYPTION implies that the cryptographer does not have pending
1554 // keys. Hence, as long as we're not trying to do an invalid passphrase
1555 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
1556 // will succeed. If for some reason a new encryption key arrives via
1557 // sync later, the SBH will trigger another OnPassphraseRequired().
1558 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1559 NotifyObservers();
1561 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
1564 bool ProfileSyncService::SetDecryptionPassphrase(
1565 const std::string& passphrase) {
1566 if (IsPassphraseRequired()) {
1567 DVLOG(1) << "Setting passphrase for decryption.";
1568 return backend_->SetDecryptionPassphrase(passphrase);
1569 } else {
1570 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
1571 "IsPassphraseRequired() is false.";
1572 return false;
1576 void ProfileSyncService::EnableEncryptEverything() {
1577 // Tests override sync_initialized() to always return true, so we
1578 // must check that instead of |backend_initialized_|.
1579 // TODO(akalin): Fix the above. :/
1580 DCHECK(sync_initialized());
1581 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
1582 // problems around cancelling encryption in the background (crbug.com/119649).
1583 if (!encrypt_everything_)
1584 encryption_pending_ = true;
1585 UMA_HISTOGRAM_BOOLEAN("Sync.EncryptAllData", true);
1588 bool ProfileSyncService::encryption_pending() const {
1589 // We may be called during the setup process before we're
1590 // initialized (via IsEncryptedDatatypeEnabled and
1591 // IsPassphraseRequiredForDecryption).
1592 return encryption_pending_;
1595 bool ProfileSyncService::EncryptEverythingEnabled() const {
1596 DCHECK(backend_initialized_);
1597 return encrypt_everything_ || encryption_pending_;
1600 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
1601 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1602 // We may be called during the setup process before we're
1603 // initialized. In this case, we default to the sensitive types.
1604 return encrypted_types_;
1607 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
1608 NotifyObservers();
1609 if (is_sync_managed) {
1610 DisableForUser();
1611 } else if (HasSyncSetupCompleted() &&
1612 IsSyncEnabledAndLoggedIn() &&
1613 IsSyncTokenAvailable()) {
1614 // Previously-configured sync has been re-enabled, so start sync now.
1615 StartUp();
1619 void ProfileSyncService::Observe(int type,
1620 const content::NotificationSource& source,
1621 const content::NotificationDetails& details) {
1622 switch (type) {
1623 case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL: {
1624 const GoogleServiceSigninSuccessDetails* successful =
1625 content::Details<const GoogleServiceSigninSuccessDetails>(
1626 details).ptr();
1627 DCHECK(!successful->password.empty());
1628 if (!sync_prefs_.IsStartSuppressed()) {
1629 cached_passphrase_ = successful->password;
1630 // Try to consume the passphrase we just cached. If the sync backend
1631 // is not running yet, the passphrase will remain cached until the
1632 // backend starts up.
1633 ConsumeCachedPassphraseIfPossible();
1635 #if defined(OS_CHROMEOS)
1636 RefreshSpareBootstrapToken(successful->password);
1637 #endif
1638 if (!sync_initialized() ||
1639 GetAuthError().state() != AuthError::NONE) {
1640 // Track the fact that we're still waiting for auth to complete.
1641 is_auth_in_progress_ = true;
1643 break;
1645 case chrome::NOTIFICATION_TOKEN_REQUEST_FAILED: {
1646 const TokenService::TokenRequestFailedDetails& token_details =
1647 *(content::Details<const TokenService::TokenRequestFailedDetails>(
1648 details).ptr());
1649 if (IsTokenServiceRelevant(token_details.service()) &&
1650 !IsSyncTokenAvailable()) {
1651 // The additional check around IsSyncTokenAvailable() above prevents us
1652 // sounding the alarm if we actually have a valid token but a refresh
1653 // attempt by TokenService failed for any variety of reasons (e.g. flaky
1654 // network). It's possible the token we do have is also invalid, but in
1655 // that case we should already have (or can expect) an auth error sent
1656 // from the sync backend.
1657 AuthError error(AuthError::INVALID_GAIA_CREDENTIALS);
1658 UpdateAuthErrorState(error);
1660 break;
1662 case chrome::NOTIFICATION_TOKEN_AVAILABLE: {
1663 const TokenService::TokenAvailableDetails& token_details =
1664 *(content::Details<const TokenService::TokenAvailableDetails>(
1665 details).ptr());
1666 if (IsTokenServiceRelevant(token_details.service()) &&
1667 IsSyncEnabledAndLoggedIn() &&
1668 IsSyncTokenAvailable()) {
1669 if (backend_initialized_)
1670 backend_->UpdateCredentials(GetCredentials());
1671 else
1672 StartUp();
1674 break;
1676 case chrome::NOTIFICATION_TOKEN_LOADING_FINISHED: {
1677 // This notification gets fired when TokenService loads the tokens
1678 // from storage.
1679 if (IsSyncEnabledAndLoggedIn()) {
1680 // Don't start up sync and generate an auth error on auto_start
1681 // platforms as they have their own way to resolve TokenService errors.
1682 // (crbug.com/128592).
1683 if (auto_start_enabled_ && !IsSyncTokenAvailable())
1684 break;
1686 // Initialize the backend if sync is enabled. If the sync token was
1687 // not loaded, GetCredentials() will generate invalid credentials to
1688 // cause the backend to generate an auth error (crbug.com/121755).
1689 if (backend_initialized_)
1690 backend_->UpdateCredentials(GetCredentials());
1691 else
1692 StartUp();
1694 break;
1696 default: {
1697 NOTREACHED();
1702 void ProfileSyncService::AddObserver(Observer* observer) {
1703 observers_.AddObserver(observer);
1706 void ProfileSyncService::RemoveObserver(Observer* observer) {
1707 observers_.RemoveObserver(observer);
1710 bool ProfileSyncService::HasObserver(Observer* observer) const {
1711 return observers_.HasObserver(observer);
1714 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
1715 return sync_js_controller_.AsWeakPtr();
1718 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
1719 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
1722 // static
1723 bool ProfileSyncService::IsSyncEnabled() {
1724 // We have switches::kEnableSync just in case we need to change back to
1725 // sync-disabled-by-default on a platform.
1726 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync);
1729 bool ProfileSyncService::IsManaged() const {
1730 return sync_prefs_.IsManaged();
1733 bool ProfileSyncService::ShouldPushChanges() {
1734 // True only after all bootstrapping has succeeded: the sync backend
1735 // is initialized, all enabled data types are consistent with one
1736 // another, and no unrecoverable error has transpired.
1737 if (HasUnrecoverableError())
1738 return false;
1740 if (!data_type_manager_.get())
1741 return false;
1743 return data_type_manager_->state() == DataTypeManager::CONFIGURED;
1746 void ProfileSyncService::StopAndSuppress() {
1747 sync_prefs_.SetStartSuppressed(true);
1748 ShutdownImpl(false);
1751 void ProfileSyncService::UnsuppressAndStart() {
1752 DCHECK(profile_);
1753 sync_prefs_.SetStartSuppressed(false);
1754 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess
1755 // is never called for some clients.
1756 if (signin_ && signin_->GetAuthenticatedUsername().empty()) {
1757 signin_->SetAuthenticatedUsername(sync_prefs_.GetGoogleServicesUsername());
1759 TryStart();
1762 void ProfileSyncService::AcknowledgeSyncedTypes() {
1763 sync_prefs_.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
1766 void ProfileSyncService::ReconfigureDatatypeManager() {
1767 // If we haven't initialized yet, don't configure the DTM as it could cause
1768 // association to start before a Directory has even been created.
1769 if (backend_initialized_) {
1770 DCHECK(backend_.get());
1771 ConfigureDataTypeManager();
1772 } else if (HasUnrecoverableError()) {
1773 // There is nothing more to configure. So inform the listeners,
1774 NotifyObservers();
1776 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
1777 << "Unrecoverable error.";
1778 } else {
1779 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
1780 << "initialized";
1784 const FailedDatatypesHandler& ProfileSyncService::failed_datatypes_handler()
1785 const {
1786 return failed_datatypes_handler_;
1789 void ProfileSyncService::OnInternalUnrecoverableError(
1790 const tracked_objects::Location& from_here,
1791 const std::string& message,
1792 bool delete_sync_database,
1793 UnrecoverableErrorReason reason) {
1794 DCHECK(!HasUnrecoverableError());
1795 unrecoverable_error_reason_ = reason;
1796 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
1799 void ProfileSyncService::ResetForTest() {
1800 Profile* profile = profile_;
1801 SigninManager* signin = SigninManagerFactory::GetForProfile(profile);
1802 ProfileSyncService::StartBehavior behavior =
1803 browser_defaults::kSyncAutoStarts ? ProfileSyncService::AUTO_START
1804 : ProfileSyncService::MANUAL_START;
1806 // We call the destructor and placement new here because we want to explicitly
1807 // recreate a new ProfileSyncService instance at the same memory location as
1808 // the old one. Doing so is fine because this code is run only from within
1809 // integration tests, and the message loop is not running at this point.
1810 // See http://stackoverflow.com/questions/6224121/is-new-this-myclass-undefined-behaviour-after-directly-calling-the-destru.
1811 ProfileSyncService* old_this = this;
1812 this->~ProfileSyncService();
1813 new(old_this) ProfileSyncService(
1814 new ProfileSyncComponentsFactoryImpl(profile,
1815 CommandLine::ForCurrentProcess()),
1816 profile,
1817 signin,
1818 behavior);