Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blob0de45d8b65a62d59ca08e56ef0c2e8a9488007e9
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 <vector>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browsing_data/browsing_data_helper.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
33 #include "chrome/browser/net/chrome_cookie_notification_details.h"
34 #include "chrome/browser/password_manager/password_store_factory.h"
35 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
36 #include "chrome/browser/prefs/pref_service_syncable.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/signin/about_signin_internals_factory.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
43 #include "chrome/browser/sync/glue/sync_backend_host.h"
44 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
45 #include "chrome/browser/sync/glue/sync_start_util.h"
46 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
47 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
48 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
49 #include "chrome/browser/sync/sync_type_preference_provider.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_list.h"
52 #include "chrome/browser/ui/browser_window.h"
53 #include "chrome/browser/ui/global_error/global_error_service.h"
54 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
55 #include "chrome/browser/ui/sync/browser_synced_window_delegates_getter.h"
56 #include "chrome/common/channel_info.h"
57 #include "chrome/common/chrome_switches.h"
58 #include "chrome/common/pref_names.h"
59 #include "chrome/common/url_constants.h"
60 #include "chrome/grit/generated_resources.h"
61 #include "components/autofill/core/common/autofill_pref_names.h"
62 #include "components/invalidation/impl/profile_invalidation_provider.h"
63 #include "components/invalidation/public/invalidation_service.h"
64 #include "components/password_manager/core/browser/password_store.h"
65 #include "components/pref_registry/pref_registry_syncable.h"
66 #include "components/signin/core/browser/about_signin_internals.h"
67 #include "components/signin/core/browser/profile_oauth2_token_service.h"
68 #include "components/signin/core/browser/signin_manager.h"
69 #include "components/signin/core/browser/signin_metrics.h"
70 #include "components/sync_driver/backend_migrator.h"
71 #include "components/sync_driver/change_processor.h"
72 #include "components/sync_driver/data_type_controller.h"
73 #include "components/sync_driver/device_info.h"
74 #include "components/sync_driver/favicon_cache.h"
75 #include "components/sync_driver/pref_names.h"
76 #include "components/sync_driver/sync_api_component_factory.h"
77 #include "components/sync_driver/sync_driver_switches.h"
78 #include "components/sync_driver/sync_error_controller.h"
79 #include "components/sync_driver/sync_stopped_reporter.h"
80 #include "components/sync_driver/sync_util.h"
81 #include "components/sync_driver/system_encryptor.h"
82 #include "components/sync_driver/user_selectable_sync_type.h"
83 #include "components/version_info/version_info_values.h"
84 #include "content/public/browser/browser_thread.h"
85 #include "content/public/browser/notification_details.h"
86 #include "content/public/browser/notification_service.h"
87 #include "content/public/browser/notification_source.h"
88 #include "net/cookies/cookie_monster.h"
89 #include "net/url_request/url_request_context_getter.h"
90 #include "sync/api/sync_error.h"
91 #include "sync/internal_api/public/configure_reason.h"
92 #include "sync/internal_api/public/http_bridge_network_resources.h"
93 #include "sync/internal_api/public/network_resources.h"
94 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
95 #include "sync/internal_api/public/shutdown_reason.h"
96 #include "sync/internal_api/public/sync_context_proxy.h"
97 #include "sync/internal_api/public/sync_encryption_handler.h"
98 #include "sync/internal_api/public/util/experiments.h"
99 #include "sync/internal_api/public/util/sync_db_util.h"
100 #include "sync/internal_api/public/util/sync_string_conversions.h"
101 #include "sync/js/js_event_details.h"
102 #include "sync/protocol/sync.pb.h"
103 #include "sync/syncable/directory.h"
104 #include "sync/util/cryptographer.h"
105 #include "ui/base/l10n/l10n_util.h"
106 #include "ui/base/l10n/time_format.h"
108 #if defined(OS_ANDROID)
109 #include "chrome/browser/sync/glue/synced_window_delegates_getter_android.h"
110 #include "sync/internal_api/public/read_transaction.h"
111 #endif
113 using browser_sync::NotificationServiceSessionsRouter;
114 using browser_sync::ProfileSyncServiceStartBehavior;
115 using browser_sync::SessionsSyncManager;
116 using browser_sync::SyncBackendHost;
117 using sync_driver::ChangeProcessor;
118 using sync_driver::DataTypeController;
119 using sync_driver::DataTypeManager;
120 using sync_driver::DataTypeStatusTable;
121 using sync_driver::DeviceInfoSyncService;
122 using syncer::ModelType;
123 using syncer::ModelTypeSet;
124 using syncer::JsBackend;
125 using syncer::JsController;
126 using syncer::JsEventDetails;
127 using syncer::JsEventHandler;
128 using syncer::ModelSafeRoutingInfo;
129 using syncer::SyncCredentials;
130 using syncer::SyncProtocolError;
131 using syncer::WeakHandle;
133 typedef GoogleServiceAuthError AuthError;
135 const char kSyncUnrecoverableErrorHistogram[] =
136 "Sync.UnrecoverableErrors";
138 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
139 // Number of initial errors (in sequence) to ignore before applying
140 // exponential back-off rules.
143 // Initial delay for exponential back-off in ms.
144 2000,
146 // Factor by which the waiting time will be multiplied.
149 // Fuzzing percentage. ex: 10% will spread requests randomly
150 // between 90%-100% of the calculated time.
151 0.2, // 20%
153 // Maximum amount of time we are willing to delay our request in ms.
154 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
155 // RequestAccessToken on connection state change after backoff
156 1000 * 3600 * 4, // 4 hours.
158 // Time to keep an entry from being discarded even when it
159 // has no significant state, -1 to never discard.
162 // Don't use initial delay unless the last request was an error.
163 false,
166 static const base::FilePath::CharType kSyncDataFolderName[] =
167 FILE_PATH_LITERAL("Sync Data");
169 static const base::FilePath::CharType kSyncBackupDataFolderName[] =
170 FILE_PATH_LITERAL("Sync Data Backup");
172 namespace {
174 void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
175 Profile* profile,
176 base::Time start,
177 base::Time end) {
178 // BrowsingDataRemover deletes itself when it's done.
179 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
180 profile, start, end);
181 if (observer)
182 remover->AddObserver(observer);
183 remover->Remove(BrowsingDataRemover::REMOVE_ALL,
184 BrowsingDataHelper::ALL);
186 scoped_refptr<password_manager::PasswordStore> password =
187 PasswordStoreFactory::GetForProfile(profile,
188 ServiceAccessType::EXPLICIT_ACCESS);
189 password->RemoveLoginsSyncedBetween(start, end);
192 // Perform the actual sync data folder deletion.
193 // This should only be called on the sync thread.
194 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
195 if (base::DirectoryExists(directory_path)) {
196 if (!base::DeleteFile(directory_path, true))
197 LOG(DFATAL) << "Could not delete the Sync Data folder.";
201 } // anonymous namespace
203 bool ShouldShowActionOnUI(
204 const syncer::SyncProtocolError& error) {
205 return (error.action != syncer::UNKNOWN_ACTION &&
206 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
207 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
210 ProfileSyncService::ProfileSyncService(
211 scoped_ptr<sync_driver::SyncApiComponentFactory> factory,
212 Profile* profile,
213 scoped_ptr<SigninManagerWrapper> signin_wrapper,
214 ProfileOAuth2TokenService* oauth2_token_service,
215 ProfileSyncServiceStartBehavior start_behavior)
216 : OAuth2TokenService::Consumer("sync"),
217 last_auth_error_(AuthError::AuthErrorNone()),
218 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
219 factory_(factory.Pass()),
220 profile_(profile),
221 sync_prefs_(profile_->GetPrefs()),
222 sync_service_url_(
223 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
224 chrome::GetChannel())),
225 is_first_time_sync_configure_(false),
226 backend_initialized_(false),
227 sync_disabled_by_admin_(false),
228 is_auth_in_progress_(false),
229 signin_(signin_wrapper.Pass()),
230 unrecoverable_error_reason_(ERROR_REASON_UNSET),
231 expect_sync_configuration_aborted_(false),
232 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
233 encrypt_everything_allowed_(true),
234 encrypt_everything_(false),
235 encryption_pending_(false),
236 configure_status_(DataTypeManager::UNKNOWN),
237 oauth2_token_service_(oauth2_token_service),
238 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
239 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
240 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
241 network_resources_(new syncer::HttpBridgeNetworkResources),
242 backend_mode_(IDLE),
243 need_backup_(false),
244 backup_finished_(false),
245 clear_browsing_data_(base::Bind(&ClearBrowsingData)),
246 browsing_data_remover_observer_(NULL),
247 catch_up_configure_in_progress_(false),
248 passphrase_prompt_triggered_by_version_(false),
249 weak_factory_(this),
250 startup_controller_weak_factory_(this) {
251 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
252 DCHECK(profile);
253 startup_controller_.reset(new browser_sync::StartupController(
254 start_behavior,
255 oauth2_token_service,
256 &sync_prefs_,
257 signin_.get(),
258 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
259 startup_controller_weak_factory_.GetWeakPtr(),
260 SYNC)));
261 backup_rollback_controller_.reset(new browser_sync::BackupRollbackController(
262 &sync_prefs_,
263 signin_.get(),
264 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
265 startup_controller_weak_factory_.GetWeakPtr(),
266 BACKUP),
267 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
268 startup_controller_weak_factory_.GetWeakPtr(),
269 ROLLBACK)));
270 syncer::SyncableService::StartSyncFlare flare(
271 sync_start_util::GetFlareForSyncableService(profile->GetPath()));
272 scoped_ptr<browser_sync::LocalSessionEventRouter> router(
273 new NotificationServiceSessionsRouter(profile, flare));
275 DCHECK(factory_.get());
276 local_device_ = factory_->CreateLocalDeviceInfoProvider();
277 sync_stopped_reporter_.reset(
278 new browser_sync::SyncStoppedReporter(
279 sync_service_url_,
280 local_device_->GetSyncUserAgent(),
281 profile_->GetRequestContext(),
282 browser_sync::SyncStoppedReporter::ResultCallback()));
283 scoped_ptr<browser_sync::SyncedWindowDelegatesGetter> synced_window_getter(
284 #if defined(OS_ANDROID)
285 new browser_sync::SyncedWindowDelegatesGetterAndroid());
286 #else
287 new browser_sync::BrowserSyncedWindowDelegatesGetter());
288 #endif
289 sessions_sync_manager_.reset(
290 new SessionsSyncManager(profile, local_device_.get(), router.Pass(),
291 synced_window_getter.Pass()));
292 device_info_sync_service_.reset(
293 new DeviceInfoSyncService(local_device_.get()));
295 std::string last_version = sync_prefs_.GetLastRunVersion();
296 std::string current_version = PRODUCT_VERSION;
297 sync_prefs_.SetLastRunVersion(current_version);
299 // Check for a major version change. Note that the versions have format
300 // MAJOR.MINOR.BUILD.PATCH.
301 if (last_version.substr(0, last_version.find('.')) !=
302 current_version.substr(0, current_version.find('.'))) {
303 passphrase_prompt_triggered_by_version_ = true;
307 ProfileSyncService::~ProfileSyncService() {
308 sync_prefs_.RemoveSyncPrefObserver(this);
309 // Shutdown() should have been called before destruction.
310 CHECK(!backend_initialized_);
313 bool ProfileSyncService::CanSyncStart() const {
314 return IsSyncAllowed() && IsSyncRequested() && IsSignedIn();
317 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
318 if (!oauth2_token_service_)
319 return false;
321 return oauth2_token_service_->RefreshTokenIsAvailable(
322 signin_->GetAccountIdToUse());
325 void ProfileSyncService::Initialize() {
326 // We clear this here (vs Shutdown) because we want to remember that an error
327 // happened on shutdown so we can display details (message, location) about it
328 // in about:sync.
329 ClearStaleErrors();
331 sync_prefs_.AddSyncPrefObserver(this);
333 // If sync isn't allowed, the only thing to do is to turn it off.
334 if (!IsSyncAllowed()) {
335 RequestStop(CLEAR_DATA);
336 return;
339 RegisterAuthNotifications();
341 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
342 // Clean up in case of previous crash / setup abort / signout.
343 StopImpl(CLEAR_DATA);
346 TrySyncDatatypePrefRecovery();
348 #if defined(OS_CHROMEOS)
349 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
350 if (bootstrap_token.empty()) {
351 sync_prefs_.SetEncryptionBootstrapToken(
352 sync_prefs_.GetSpareBootstrapToken());
354 #endif
356 #if !defined(OS_ANDROID)
357 DCHECK(sync_error_controller_ == NULL)
358 << "Initialize() called more than once.";
359 sync_error_controller_.reset(new SyncErrorController(this));
360 AddObserver(sync_error_controller_.get());
361 #endif
363 bool running_rollback = false;
364 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
365 // Backup is needed if user's not signed in or signed in but previous
366 // backup didn't finish, i.e. backend didn't switch from backup to sync.
367 need_backup_ = !IsSignedIn() || sync_prefs_.GetFirstSyncTime().is_null();
369 // Try to resume rollback if it didn't finish in last session.
370 running_rollback = backup_rollback_controller_->StartRollback();
371 } else {
372 need_backup_ = false;
375 #if defined(ENABLE_PRE_SYNC_BACKUP)
376 if (!running_rollback && !IsSignedIn()) {
377 CleanUpBackup();
379 #else
380 DCHECK(!running_rollback);
381 #endif
383 memory_pressure_listener_.reset(new base::MemoryPressureListener(base::Bind(
384 &ProfileSyncService::OnMemoryPressure, weak_factory_.GetWeakPtr())));
385 startup_controller_->Reset(GetRegisteredDataTypes());
386 startup_controller_->TryStart();
389 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
390 DCHECK(!backend_initialized());
391 if (!HasSyncSetupCompleted())
392 return;
394 // There was a bug where OnUserChoseDatatypes was not properly called on
395 // configuration (see crbug.com/154940). We detect this by checking whether
396 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
397 // completed, it means sync was not properly configured, so we manually
398 // set kSyncKeepEverythingSynced.
399 PrefService* const pref_service = profile_->GetPrefs();
400 if (!pref_service)
401 return;
402 if (GetPreferredDataTypes().Size() > 1)
403 return;
405 const PrefService::Preference* keep_everything_synced =
406 pref_service->FindPreference(
407 sync_driver::prefs::kSyncKeepEverythingSynced);
408 // This will be false if the preference was properly set or if it's controlled
409 // by policy.
410 if (!keep_everything_synced->IsDefaultValue())
411 return;
413 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
414 // types now, before we configure.
415 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
416 sync_prefs_.SetKeepEverythingSynced(true);
417 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
420 void ProfileSyncService::StartSyncingWithServer() {
421 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
423 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
424 switches::kSyncEnableClearDataOnPassphraseEncryption) &&
425 backend_mode_ == SYNC &&
426 sync_prefs_.GetPassphraseEncryptionTransitionInProgress()) {
427 BeginConfigureCatchUpBeforeClear();
428 return;
431 if (backend_)
432 backend_->StartSyncingWithServer();
435 void ProfileSyncService::RegisterAuthNotifications() {
436 oauth2_token_service_->AddObserver(this);
437 if (signin())
438 signin()->AddObserver(this);
441 void ProfileSyncService::UnregisterAuthNotifications() {
442 if (signin())
443 signin()->RemoveObserver(this);
444 oauth2_token_service_->RemoveObserver(this);
447 void ProfileSyncService::RegisterDataTypeController(
448 sync_driver::DataTypeController* data_type_controller) {
449 DCHECK_EQ(
450 directory_data_type_controllers_.count(data_type_controller->type()),
451 0U);
452 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
453 data_type_controller->type()));
454 directory_data_type_controllers_[data_type_controller->type()] =
455 data_type_controller;
458 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
459 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
460 << "Duplicate registration of type " << ModelTypeToString(type);
462 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
463 // fixed and we have some way of telling whether or not this type should be
464 // enabled.
465 non_blocking_data_type_manager_.RegisterType(type, false);
468 void ProfileSyncService::InitializeNonBlockingType(
469 syncer::ModelType type,
470 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
471 const base::WeakPtr<syncer_v2::ModelTypeProcessorImpl>& type_processor) {
472 non_blocking_data_type_manager_.InitializeType(
473 type, task_runner, type_processor);
476 bool ProfileSyncService::IsDataTypeControllerRunning(
477 syncer::ModelType type) const {
478 DataTypeController::TypeMap::const_iterator iter =
479 directory_data_type_controllers_.find(type);
480 if (iter == directory_data_type_controllers_.end()) {
481 return false;
483 return iter->second->state() == DataTypeController::RUNNING;
486 sync_driver::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
487 if (!IsDataTypeControllerRunning(syncer::SESSIONS))
488 return NULL;
489 return sessions_sync_manager_.get();
492 browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
493 return sessions_sync_manager_->GetFaviconCache();
496 browser_sync::SyncedWindowDelegatesGetter*
497 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
498 return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
501 sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
502 const {
503 return device_info_sync_service_.get();
506 sync_driver::LocalDeviceInfoProvider*
507 ProfileSyncService::GetLocalDeviceInfoProvider() const {
508 return local_device_.get();
511 void ProfileSyncService::GetDataTypeControllerStates(
512 DataTypeController::StateMap* state_map) const {
513 for (DataTypeController::TypeMap::const_iterator iter =
514 directory_data_type_controllers_.begin();
515 iter != directory_data_type_controllers_.end();
516 ++iter)
517 (*state_map)[iter->first] = iter->second.get()->state();
520 SyncCredentials ProfileSyncService::GetCredentials() {
521 SyncCredentials credentials;
522 if (backend_mode_ == SYNC) {
523 credentials.email = signin_->GetEffectiveUsername();
524 DCHECK(!credentials.email.empty());
525 credentials.sync_token = access_token_;
527 if (credentials.sync_token.empty())
528 credentials.sync_token = "credentials_lost";
530 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
533 return credentials;
536 bool ProfileSyncService::ShouldDeleteSyncFolder() {
537 switch (backend_mode_) {
538 case SYNC:
539 return !HasSyncSetupCompleted();
540 case BACKUP:
541 return true;
542 case ROLLBACK:
543 return false;
544 case IDLE:
545 NOTREACHED();
546 return true;
548 return true;
551 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
552 if (!backend_) {
553 NOTREACHED();
554 return;
557 SyncCredentials credentials = GetCredentials();
559 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
560 profile_->GetRequestContext());
562 if (backend_mode_ == SYNC && delete_stale_data)
563 ClearStaleErrors();
565 backend_->Initialize(this, sync_thread_.Pass(), GetJsEventHandler(),
566 sync_service_url_,
567 local_device_->GetSyncUserAgent(),
568 credentials, delete_stale_data,
569 scoped_ptr<syncer::SyncManagerFactory>(
570 new syncer::SyncManagerFactory(GetManagerType()))
571 .Pass(),
572 MakeWeakHandle(weak_factory_.GetWeakPtr()),
573 base::Bind(browser_sync::ChromeReportUnrecoverableError),
574 network_resources_.get(), saved_nigori_state_.Pass());
577 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
578 if (encryption_pending())
579 return true;
580 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
581 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
582 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
583 return !Intersection(preferred_types, encrypted_types).Empty();
586 void ProfileSyncService::OnProtocolEvent(
587 const syncer::ProtocolEvent& event) {
588 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
589 protocol_event_observers_,
590 OnProtocolEvent(event));
593 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
594 syncer::ModelType type,
595 const syncer::CommitCounters& counters) {
596 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
597 type_debug_info_observers_,
598 OnCommitCountersUpdated(type, counters));
601 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
602 syncer::ModelType type,
603 const syncer::UpdateCounters& counters) {
604 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
605 type_debug_info_observers_,
606 OnUpdateCountersUpdated(type, counters));
609 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
610 syncer::ModelType type,
611 const syncer::StatusCounters& counters) {
612 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
613 type_debug_info_observers_,
614 OnStatusCountersUpdated(type, counters));
617 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
618 syncer::ModelType type) {
619 DCHECK(syncer::UserTypes().Has(type));
621 if (!GetPreferredDataTypes().Has(type)) {
622 // We can get here as datatype SyncableServices are typically wired up
623 // to the native datatype even if sync isn't enabled.
624 DVLOG(1) << "Dropping sync startup request because type "
625 << syncer::ModelTypeToString(type) << "not enabled.";
626 return;
629 // If this is a data type change after a major version update, reset the
630 // passphrase prompted state and notify observers.
631 if (IsPassphraseRequired() && passphrase_prompt_triggered_by_version_) {
632 // The major version has changed and a local syncable change was made.
633 // Reset the passphrase prompt state.
634 passphrase_prompt_triggered_by_version_ = false;
635 sync_prefs_.SetPassphrasePrompted(false);
636 NotifyObservers();
639 if (backend_.get()) {
640 DVLOG(1) << "A data type requested sync startup, but it looks like "
641 "something else beat it to the punch.";
642 return;
645 startup_controller_->OnDataTypeRequestsSyncStartup(type);
648 void ProfileSyncService::StartUpSlowBackendComponents(
649 ProfileSyncService::BackendMode mode) {
650 DCHECK_NE(IDLE, mode);
651 if (backend_mode_ == mode) {
652 return;
655 // Backend mode transition rules:
656 // * can transit from IDLE to any other non-IDLE mode.
657 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
658 // be explicitly shut down before backup/rollback starts.
659 // * can not transit out of ROLLBACK mode until rollback is finished
660 // (successfully or unsuccessfully).
661 // * can not transit out of BACKUP mode until backup is finished
662 // (successfully or unsuccessfully).
663 // * if backup is needed, can only transit to SYNC if backup is finished,
665 if (backend_mode_ == SYNC) {
666 LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
667 return;
670 if (backend_mode_ == ROLLBACK ||
671 (backend_mode_ == BACKUP && !backup_finished_)) {
672 // Wait for rollback/backup to finish before start new backend.
673 return;
676 if (mode == SYNC && NeedBackup() && !backup_finished_) {
677 if (backend_mode_ != BACKUP)
678 backup_rollback_controller_->StartBackup();
679 return;
682 DVLOG(1) << "Start backend mode: " << mode;
684 if (backend_) {
685 if (mode == SYNC)
686 ShutdownImpl(syncer::SWITCH_MODE_SYNC);
687 else
688 ShutdownImpl(syncer::STOP_SYNC);
691 backend_mode_ = mode;
693 if (backend_mode_ == BACKUP)
694 backup_start_time_ = base::Time::Now();
696 if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
697 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
698 base::Time::Now() - backup_start_time_);
699 backup_start_time_ = base::Time();
702 if (backend_mode_ == ROLLBACK)
703 ClearBrowsingDataSinceFirstSync();
704 else if (backend_mode_ == SYNC)
705 CheckSyncBackupIfNeeded();
707 base::FilePath sync_folder = backend_mode_ == SYNC ?
708 base::FilePath(kSyncDataFolderName) :
709 base::FilePath(kSyncBackupDataFolderName);
711 invalidation::InvalidationService* invalidator = NULL;
712 if (backend_mode_ == SYNC) {
713 invalidation::ProfileInvalidationProvider* provider =
714 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
715 profile_);
716 if (provider)
717 invalidator = provider->GetInvalidationService();
720 directory_path_ = profile_->GetPath().Append(sync_folder);
722 backend_.reset(
723 factory_->CreateSyncBackendHost(
724 profile_->GetDebugName(),
725 invalidator,
726 sync_prefs_.AsWeakPtr(),
727 sync_folder));
729 // Initialize the backend. Every time we start up a new SyncBackendHost,
730 // we'll want to start from a fresh SyncDB, so delete any old one that might
731 // be there.
732 InitializeBackend(ShouldDeleteSyncFolder());
734 UpdateFirstSyncTimePref();
736 ReportPreviousSessionMemoryWarningCount();
739 void ProfileSyncService::OnGetTokenSuccess(
740 const OAuth2TokenService::Request* request,
741 const std::string& access_token,
742 const base::Time& expiration_time) {
743 DCHECK_EQ(access_token_request_, request);
744 access_token_request_.reset();
745 access_token_ = access_token;
746 token_receive_time_ = base::Time::Now();
747 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
749 if (sync_prefs_.SyncHasAuthError()) {
750 sync_prefs_.SetSyncAuthError(false);
751 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
752 AUTH_ERROR_FIXED,
753 AUTH_ERROR_LIMIT);
756 if (HasSyncingBackend())
757 backend_->UpdateCredentials(GetCredentials());
758 else
759 startup_controller_->TryStart();
762 void ProfileSyncService::OnGetTokenFailure(
763 const OAuth2TokenService::Request* request,
764 const GoogleServiceAuthError& error) {
765 DCHECK_EQ(access_token_request_, request);
766 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
767 access_token_request_.reset();
768 last_get_token_error_ = error;
769 switch (error.state()) {
770 case GoogleServiceAuthError::CONNECTION_FAILED:
771 case GoogleServiceAuthError::REQUEST_CANCELED:
772 case GoogleServiceAuthError::SERVICE_ERROR:
773 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
774 // Transient error. Retry after some time.
775 request_access_token_backoff_.InformOfRequest(false);
776 next_token_request_time_ = base::Time::Now() +
777 request_access_token_backoff_.GetTimeUntilRelease();
778 request_access_token_retry_timer_.Start(
779 FROM_HERE,
780 request_access_token_backoff_.GetTimeUntilRelease(),
781 base::Bind(&ProfileSyncService::RequestAccessToken,
782 weak_factory_.GetWeakPtr()));
783 NotifyObservers();
784 break;
786 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
787 if (!sync_prefs_.SyncHasAuthError()) {
788 sync_prefs_.SetSyncAuthError(true);
789 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
790 AUTH_ERROR_ENCOUNTERED,
791 AUTH_ERROR_LIMIT);
793 // Fallthrough.
795 default: {
796 if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
797 LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
799 // Show error to user.
800 UpdateAuthErrorState(error);
805 void ProfileSyncService::OnRefreshTokenAvailable(
806 const std::string& account_id) {
807 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
808 // fixed.
809 tracked_objects::ScopedTracker tracking_profile(
810 FROM_HERE_WITH_EXPLICIT_FUNCTION(
811 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
813 if (account_id == signin_->GetAccountIdToUse())
814 OnRefreshTokensLoaded();
817 void ProfileSyncService::OnRefreshTokenRevoked(
818 const std::string& account_id) {
819 if (!IsOAuthRefreshTokenAvailable()) {
820 access_token_.clear();
821 // The additional check around IsOAuthRefreshTokenAvailable() above
822 // prevents us sounding the alarm if we actually have a valid token but
823 // a refresh attempt failed for any variety of reasons
824 // (e.g. flaky network). It's possible the token we do have is also
825 // invalid, but in that case we should already have (or can expect) an
826 // auth error sent from the sync backend.
827 UpdateAuthErrorState(
828 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
832 void ProfileSyncService::OnRefreshTokensLoaded() {
833 // This notification gets fired when OAuth2TokenService loads the tokens
834 // from storage.
835 // Initialize the backend if sync is enabled. If the sync token was
836 // not loaded, GetCredentials() will generate invalid credentials to
837 // cause the backend to generate an auth error (crbug.com/121755).
838 if (HasSyncingBackend()) {
839 RequestAccessToken();
840 } else {
841 startup_controller_->TryStart();
845 void ProfileSyncService::Shutdown() {
846 UnregisterAuthNotifications();
848 ShutdownImpl(syncer::BROWSER_SHUTDOWN);
849 if (sync_error_controller_) {
850 // Destroy the SyncErrorController when the service shuts down for good.
851 RemoveObserver(sync_error_controller_.get());
852 sync_error_controller_.reset();
855 if (sync_thread_)
856 sync_thread_->Stop();
859 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
860 if (!backend_) {
861 if (reason == syncer::ShutdownReason::DISABLE_SYNC && sync_thread_) {
862 // If the backend is already shut down when a DISABLE_SYNC happens,
863 // the data directory needs to be cleaned up here.
864 sync_thread_->task_runner()->PostTask(
865 FROM_HERE, base::Bind(&DeleteSyncDataFolder, directory_path_));
867 return;
870 if (reason == syncer::ShutdownReason::STOP_SYNC
871 || reason == syncer::ShutdownReason::DISABLE_SYNC) {
872 RemoveClientFromServer();
875 non_blocking_data_type_manager_.DisconnectSyncBackend();
877 // First, we spin down the backend to stop change processing as soon as
878 // possible.
879 base::Time shutdown_start_time = base::Time::Now();
880 backend_->StopSyncingForShutdown();
882 // Stop all data type controllers, if needed. Note that until Stop
883 // completes, it is possible in theory to have a ChangeProcessor apply a
884 // change from a native model. In that case, it will get applied to the sync
885 // database (which doesn't get destroyed until we destroy the backend below)
886 // as an unsynced change. That will be persisted, and committed on restart.
887 if (directory_data_type_manager_) {
888 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
889 // When aborting as part of shutdown, we should expect an aborted sync
890 // configure result, else we'll dcheck when we try to read the sync error.
891 expect_sync_configuration_aborted_ = true;
892 directory_data_type_manager_->Stop();
894 directory_data_type_manager_.reset();
897 // Shutdown the migrator before the backend to ensure it doesn't pull a null
898 // snapshot.
899 migrator_.reset();
900 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
902 // Move aside the backend so nobody else tries to use it while we are
903 // shutting it down.
904 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
905 if (doomed_backend) {
906 sync_thread_ = doomed_backend->Shutdown(reason);
907 doomed_backend.reset();
909 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
910 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
912 weak_factory_.InvalidateWeakPtrs();
914 if (backend_mode_ == SYNC)
915 startup_controller_->Reset(GetRegisteredDataTypes());
917 // Don't let backup block sync regardless backup succeeded or not.
918 if (backend_mode_ == BACKUP)
919 backup_finished_ = true;
921 // Sync could be blocked by rollback/backup. Post task to check whether sync
922 // should start after shutting down rollback/backup backend.
923 if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
924 reason != syncer::SWITCH_MODE_SYNC &&
925 reason != syncer::BROWSER_SHUTDOWN) {
926 base::ThreadTaskRunnerHandle::Get()->PostTask(
927 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
928 startup_controller_weak_factory_.GetWeakPtr()));
931 // Clear various flags.
932 backend_mode_ = IDLE;
933 expect_sync_configuration_aborted_ = false;
934 is_auth_in_progress_ = false;
935 backend_initialized_ = false;
936 cached_passphrase_.clear();
937 encryption_pending_ = false;
938 encrypt_everything_ = false;
939 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
940 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
941 catch_up_configure_in_progress_ = false;
942 request_access_token_retry_timer_.Stop();
943 // Revert to "no auth error".
944 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
945 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
947 NotifyObservers();
949 // Mark this as a clean shutdown(without crash).
950 sync_prefs_.SetCleanShutdown(true);
953 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate) {
954 switch (data_fate) {
955 case KEEP_DATA:
956 // TODO(maxbogue): Investigate whether this logic can/should be moved
957 // into ShutdownImpl or SyncBackendHost itself.
958 if (HasSyncingBackend()) {
959 backend_->UnregisterInvalidationIds();
961 ShutdownImpl(syncer::STOP_SYNC);
962 break;
963 case CLEAR_DATA:
964 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
965 // PSS clients don't think we're set up while we're shutting down.
966 sync_prefs_.ClearPreferences();
967 ClearUnrecoverableError();
968 ShutdownImpl(syncer::DISABLE_SYNC);
969 break;
973 bool ProfileSyncService::HasSyncSetupCompleted() const {
974 return sync_prefs_.HasSyncSetupCompleted();
977 void ProfileSyncService::SetSyncSetupCompleted() {
978 sync_prefs_.SetSyncSetupCompleted();
981 void ProfileSyncService::UpdateLastSyncedTime() {
982 sync_prefs_.SetLastSyncedTime(base::Time::Now());
985 void ProfileSyncService::NotifyObservers() {
986 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
987 OnStateChanged());
990 void ProfileSyncService::NotifySyncCycleCompleted() {
991 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
992 OnSyncCycleCompleted());
995 void ProfileSyncService::ClearStaleErrors() {
996 ClearUnrecoverableError();
997 last_actionable_error_ = SyncProtocolError();
998 // Clear the data type errors as well.
999 if (directory_data_type_manager_.get())
1000 directory_data_type_manager_->ResetDataTypeErrors();
1004 void ProfileSyncService::ClearUnrecoverableError() {
1005 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
1006 unrecoverable_error_message_.clear();
1007 unrecoverable_error_location_ = tracked_objects::Location();
1010 // An invariant has been violated. Transition to an error state where we try
1011 // to do as little work as possible, to avoid further corruption or crashes.
1012 void ProfileSyncService::OnUnrecoverableError(
1013 const tracked_objects::Location& from_here,
1014 const std::string& message) {
1015 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
1016 // interface are assumed to originate within the syncer.
1017 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
1018 OnUnrecoverableErrorImpl(from_here, message, true);
1021 void ProfileSyncService::OnUnrecoverableErrorImpl(
1022 const tracked_objects::Location& from_here,
1023 const std::string& message,
1024 bool delete_sync_database) {
1025 DCHECK(HasUnrecoverableError());
1026 unrecoverable_error_message_ = message;
1027 unrecoverable_error_location_ = from_here;
1029 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
1030 unrecoverable_error_reason_,
1031 ERROR_REASON_LIMIT);
1032 std::string location;
1033 from_here.Write(true, true, &location);
1034 LOG(ERROR)
1035 << "Unrecoverable error detected at " << location
1036 << " -- ProfileSyncService unusable: " << message;
1038 // Shut all data types down.
1039 base::ThreadTaskRunnerHandle::Get()->PostTask(
1040 FROM_HERE,
1041 base::Bind(
1042 &ProfileSyncService::ShutdownImpl, weak_factory_.GetWeakPtr(),
1043 delete_sync_database ? syncer::DISABLE_SYNC : syncer::STOP_SYNC));
1046 void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
1047 if (!backend_initialized_)
1048 return;
1049 directory_data_type_manager_->ReenableType(type);
1052 void ProfileSyncService::UpdateBackendInitUMA(bool success) {
1053 if (backend_mode_ != SYNC)
1054 return;
1056 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
1058 if (is_first_time_sync_configure_) {
1059 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
1060 } else {
1061 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
1064 base::Time on_backend_initialized_time = base::Time::Now();
1065 base::TimeDelta delta = on_backend_initialized_time -
1066 startup_controller_->start_backend_time();
1067 if (is_first_time_sync_configure_) {
1068 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1069 } else {
1070 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1074 void ProfileSyncService::PostBackendInitialization() {
1075 // Never get here for backup / restore.
1076 DCHECK_EQ(backend_mode_, SYNC);
1078 if (last_backup_time_) {
1079 DCHECK(device_info_sync_service_);
1080 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1083 if (protocol_event_observers_.might_have_observers()) {
1084 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1087 non_blocking_data_type_manager_.ConnectSyncBackend(
1088 backend_->GetSyncContextProxy());
1090 if (type_debug_info_observers_.might_have_observers()) {
1091 backend_->EnableDirectoryTypeDebugInfoForwarding();
1094 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1095 // backend is initialized. We want to call this before notifying observers in
1096 // case this operation affects the "passphrase required" status.
1097 ConsumeCachedPassphraseIfPossible();
1099 // The very first time the backend initializes is effectively the first time
1100 // we can say we successfully "synced". LastSyncedTime will only be null in
1101 // this case, because the pref wasn't restored on StartUp.
1102 if (sync_prefs_.GetLastSyncedTime().is_null()) {
1103 UpdateLastSyncedTime();
1106 if (startup_controller_->auto_start_enabled() && !FirstSetupInProgress()) {
1107 // Backend is initialized but we're not in sync setup, so this must be an
1108 // autostart - mark our sync setup as completed and we'll start syncing
1109 // below.
1110 SetSyncSetupCompleted();
1113 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1114 // data type configuration because observer may flag setup as complete and
1115 // trigger data type configuration.
1116 if (HasSyncSetupCompleted()) {
1117 ConfigureDataTypeManager();
1118 } else {
1119 DCHECK(FirstSetupInProgress());
1122 NotifyObservers();
1125 void ProfileSyncService::OnBackendInitialized(
1126 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1127 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1128 debug_info_listener,
1129 const std::string& cache_guid,
1130 bool success) {
1131 UpdateBackendInitUMA(success);
1133 if (!success) {
1134 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1135 // and surface error UI to alert the user sync has stopped.
1136 // Keep the directory around for now so that on restart we will retry
1137 // again and potentially succeed in presence of transient file IO failures
1138 // or permissions issues, etc.
1140 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1141 // Unlike every other UnrecoverableError, it does not delete our sync data.
1142 // This exception made sense at the time it was implemented, but our new
1143 // directory corruption recovery mechanism makes it obsolete. By the time
1144 // we get here, we will have already tried and failed to delete the
1145 // directory. It would be no big deal if we tried to delete it again.
1146 OnInternalUnrecoverableError(FROM_HERE,
1147 "BackendInitialize failure",
1148 false,
1149 ERROR_REASON_BACKEND_INIT_FAILURE);
1150 return;
1153 backend_initialized_ = true;
1155 sync_js_controller_.AttachJsBackend(js_backend);
1156 debug_info_listener_ = debug_info_listener;
1158 SigninClient* signin_client =
1159 ChromeSigninClientFactory::GetForProfile(profile_);
1160 DCHECK(signin_client);
1161 std::string signin_scoped_device_id =
1162 signin_client->GetSigninScopedDeviceId();
1164 // Initialize local device info.
1165 local_device_->Initialize(cache_guid, signin_scoped_device_id);
1167 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1168 non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1170 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1171 ConfigureDataTypeManager();
1172 else
1173 PostBackendInitialization();
1176 void ProfileSyncService::OnSyncCycleCompleted() {
1177 UpdateLastSyncedTime();
1178 if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1179 // Trigger garbage collection of old sessions now that we've downloaded
1180 // any new session data.
1181 base::ThreadTaskRunnerHandle::Get()->PostTask(
1182 FROM_HERE, base::Bind(&SessionsSyncManager::DoGarbageCollection,
1183 base::AsWeakPtr(sessions_sync_manager_.get())));
1185 DVLOG(2) << "Notifying observers sync cycle completed";
1186 NotifySyncCycleCompleted();
1189 void ProfileSyncService::OnExperimentsChanged(
1190 const syncer::Experiments& experiments) {
1191 if (current_experiments_.Matches(experiments))
1192 return;
1194 current_experiments_ = experiments;
1196 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1197 experiments.gcm_invalidations_enabled);
1198 profile()->GetPrefs()->SetBoolean(
1199 autofill::prefs::kAutofillWalletSyncExperimentEnabled,
1200 experiments.wallet_sync_enabled);
1203 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1204 is_auth_in_progress_ = false;
1205 last_auth_error_ = error;
1207 NotifyObservers();
1210 namespace {
1212 AuthError ConnectionStatusToAuthError(
1213 syncer::ConnectionStatus status) {
1214 switch (status) {
1215 case syncer::CONNECTION_OK:
1216 return AuthError::AuthErrorNone();
1217 break;
1218 case syncer::CONNECTION_AUTH_ERROR:
1219 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1220 break;
1221 case syncer::CONNECTION_SERVER_ERROR:
1222 return AuthError(AuthError::CONNECTION_FAILED);
1223 break;
1224 default:
1225 NOTREACHED();
1226 return AuthError(AuthError::CONNECTION_FAILED);
1230 } // namespace
1232 void ProfileSyncService::OnConnectionStatusChange(
1233 syncer::ConnectionStatus status) {
1234 connection_status_update_time_ = base::Time::Now();
1235 connection_status_ = status;
1236 if (status == syncer::CONNECTION_AUTH_ERROR) {
1237 // Sync server returned error indicating that access token is invalid. It
1238 // could be either expired or access is revoked. Let's request another
1239 // access token and if access is revoked then request for token will fail
1240 // with corresponding error. If access token is repeatedly reported
1241 // invalid, there may be some issues with server, e.g. authentication
1242 // state is inconsistent on sync and token server. In that case, we
1243 // backoff token requests exponentially to avoid hammering token server
1244 // too much and to avoid getting same token due to token server's caching
1245 // policy. |request_access_token_retry_timer_| is used to backoff request
1246 // triggered by both auth error and failure talking to GAIA server.
1247 // Therefore, we're likely to reach the backoff ceiling more quickly than
1248 // you would expect from looking at the BackoffPolicy if both types of
1249 // errors happen. We shouldn't receive two errors back-to-back without
1250 // attempting a token/sync request in between, thus crank up request delay
1251 // unnecessary. This is because we won't make a sync request if we hit an
1252 // error until GAIA succeeds at sending a new token, and we won't request
1253 // a new token unless sync reports a token failure. But to be safe, don't
1254 // schedule request if this happens.
1255 if (request_access_token_retry_timer_.IsRunning()) {
1256 // The timer to perform a request later is already running; nothing
1257 // further needs to be done at this point.
1258 } else if (request_access_token_backoff_.failure_count() == 0) {
1259 // First time request without delay. Currently invalid token is used
1260 // to initialize sync backend and we'll always end up here. We don't
1261 // want to delay initialization.
1262 request_access_token_backoff_.InformOfRequest(false);
1263 RequestAccessToken();
1264 } else {
1265 request_access_token_backoff_.InformOfRequest(false);
1266 request_access_token_retry_timer_.Start(
1267 FROM_HERE,
1268 request_access_token_backoff_.GetTimeUntilRelease(),
1269 base::Bind(&ProfileSyncService::RequestAccessToken,
1270 weak_factory_.GetWeakPtr()));
1272 } else {
1273 // Reset backoff time after successful connection.
1274 if (status == syncer::CONNECTION_OK) {
1275 // Request shouldn't be scheduled at this time. But if it is, it's
1276 // possible that sync flips between OK and auth error states rapidly,
1277 // thus hammers token server. To be safe, only reset backoff delay when
1278 // no scheduled request.
1279 if (request_access_token_retry_timer_.IsRunning()) {
1280 NOTREACHED();
1281 } else {
1282 request_access_token_backoff_.Reset();
1286 const GoogleServiceAuthError auth_error =
1287 ConnectionStatusToAuthError(status);
1288 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1289 UpdateAuthErrorState(auth_error);
1293 void ProfileSyncService::OnPassphraseRequired(
1294 syncer::PassphraseRequiredReason reason,
1295 const sync_pb::EncryptedData& pending_keys) {
1296 DCHECK(backend_.get());
1297 DCHECK(backend_->IsNigoriEnabled());
1299 // TODO(lipalani) : add this check to other locations as well.
1300 if (HasUnrecoverableError()) {
1301 // When unrecoverable error is detected we post a task to shutdown the
1302 // backend. The task might not have executed yet.
1303 return;
1306 DVLOG(1) << "Passphrase required with reason: "
1307 << syncer::PassphraseRequiredReasonToString(reason);
1308 passphrase_required_reason_ = reason;
1310 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1311 if (directory_data_type_manager_) {
1312 // Reconfigure without the encrypted types (excluded implicitly via the
1313 // failed datatypes handler).
1314 directory_data_type_manager_->Configure(types,
1315 syncer::CONFIGURE_REASON_CRYPTO);
1318 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1320 // Notify observers that the passphrase status may have changed.
1321 NotifyObservers();
1324 void ProfileSyncService::OnPassphraseAccepted() {
1325 DVLOG(1) << "Received OnPassphraseAccepted.";
1327 // If the pending keys were resolved via keystore, it's possible we never
1328 // consumed our cached passphrase. Clear it now.
1329 if (!cached_passphrase_.empty())
1330 cached_passphrase_.clear();
1332 // Reset passphrase_required_reason_ since we know we no longer require the
1333 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1334 // because that can be called by OnPassphraseRequired() if no encrypted data
1335 // types are enabled, and we don't want to clobber the true passphrase error.
1336 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1338 // Make sure the data types that depend on the passphrase are started at
1339 // this time.
1340 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1341 if (directory_data_type_manager_) {
1342 // Re-enable any encrypted types if necessary.
1343 directory_data_type_manager_->Configure(types,
1344 syncer::CONFIGURE_REASON_CRYPTO);
1347 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1349 NotifyObservers();
1352 void ProfileSyncService::OnEncryptedTypesChanged(
1353 syncer::ModelTypeSet encrypted_types,
1354 bool encrypt_everything) {
1355 encrypted_types_ = encrypted_types;
1356 encrypt_everything_ = encrypt_everything;
1357 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1358 DVLOG(1) << "Encrypted types changed to "
1359 << syncer::ModelTypeSetToString(encrypted_types_)
1360 << " (encrypt everything is set to "
1361 << (encrypt_everything_ ? "true" : "false") << ")";
1362 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1364 NotifyObservers();
1367 void ProfileSyncService::OnEncryptionComplete() {
1368 DVLOG(1) << "Encryption complete";
1369 if (encryption_pending_ && encrypt_everything_) {
1370 encryption_pending_ = false;
1371 // This is to nudge the integration tests when encryption is
1372 // finished.
1373 NotifyObservers();
1377 void ProfileSyncService::OnMigrationNeededForTypes(
1378 syncer::ModelTypeSet types) {
1379 DCHECK(backend_initialized_);
1380 DCHECK(directory_data_type_manager_.get());
1382 // Migrator must be valid, because we don't sync until it is created and this
1383 // callback originates from a sync cycle.
1384 migrator_->MigrateTypes(types);
1387 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1388 last_actionable_error_ = error;
1389 DCHECK_NE(last_actionable_error_.action,
1390 syncer::UNKNOWN_ACTION);
1391 switch (error.action) {
1392 case syncer::UPGRADE_CLIENT:
1393 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1394 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1395 case syncer::STOP_AND_RESTART_SYNC:
1396 // TODO(lipalani) : if setup in progress we want to display these
1397 // actions in the popup. The current experience might not be optimal for
1398 // the user. We just dismiss the dialog.
1399 if (startup_controller_->setup_in_progress()) {
1400 RequestStop(CLEAR_DATA);
1401 expect_sync_configuration_aborted_ = true;
1403 // Trigger an unrecoverable error to stop syncing.
1404 OnInternalUnrecoverableError(FROM_HERE,
1405 last_actionable_error_.error_description,
1406 true,
1407 ERROR_REASON_ACTIONABLE_ERROR);
1408 break;
1409 case syncer::DISABLE_SYNC_AND_ROLLBACK:
1410 backup_rollback_controller_->OnRollbackReceived();
1411 // Fall through to shutdown backend and sign user out.
1412 case syncer::DISABLE_SYNC_ON_CLIENT:
1413 RequestStop(CLEAR_DATA);
1414 #if !defined(OS_CHROMEOS)
1415 // On desktop Chrome, sign out the user after a dashboard clear.
1416 // Skip sign out on ChromeOS/Android.
1417 if (!startup_controller_->auto_start_enabled()) {
1418 SigninManagerFactory::GetForProfile(profile_)->SignOut(
1419 signin_metrics::SERVER_FORCED_DISABLE);
1421 #endif
1422 break;
1423 case syncer::ROLLBACK_DONE:
1424 backup_rollback_controller_->OnRollbackDone();
1425 break;
1426 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1427 // Sync disabled by domain admin. we should stop syncing until next
1428 // restart.
1429 sync_disabled_by_admin_ = true;
1430 ShutdownImpl(syncer::DISABLE_SYNC);
1431 break;
1432 default:
1433 NOTREACHED();
1435 NotifyObservers();
1437 if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1438 (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1439 !backup_rollback_controller_->StartRollback())) {
1440 // Clean up backup data for sign-out only or when rollback is disabled.
1441 CleanUpBackup();
1442 } else if (error.action == syncer::ROLLBACK_DONE) {
1443 // Shut down ROLLBACK backend and delete backup DB.
1444 ShutdownImpl(syncer::DISABLE_SYNC);
1445 sync_prefs_.ClearFirstSyncTime();
1449 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1450 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) {
1451 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1452 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1453 switches::kSyncEnableClearDataOnPassphraseEncryption))
1454 return;
1456 // At this point the user has set a custom passphrase and we have received the
1457 // updated nigori state. Time to cache the nigori state, and catch up the
1458 // active data types.
1459 sync_prefs_.SetSavedNigoriStateForPassphraseEncryptionTransition(
1460 nigori_state);
1461 sync_prefs_.SetPassphraseEncryptionTransitionInProgress(true);
1462 BeginConfigureCatchUpBeforeClear();
1465 void ProfileSyncService::BeginConfigureCatchUpBeforeClear() {
1466 DCHECK_EQ(backend_mode_, SYNC);
1467 DCHECK(directory_data_type_manager_);
1468 DCHECK(!saved_nigori_state_);
1469 saved_nigori_state_ =
1470 sync_prefs_.GetSavedNigoriStateForPassphraseEncryptionTransition().Pass();
1471 const syncer::ModelTypeSet types = GetActiveDataTypes();
1472 catch_up_configure_in_progress_ = true;
1473 directory_data_type_manager_->Configure(types,
1474 syncer::CONFIGURE_REASON_CATCH_UP);
1477 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() {
1478 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1479 backend_->ClearServerData(base::Bind(
1480 &ProfileSyncService::OnClearServerDataDone, weak_factory_.GetWeakPtr()));
1483 void ProfileSyncService::OnClearServerDataDone() {
1484 DCHECK(sync_prefs_.GetPassphraseEncryptionTransitionInProgress());
1485 sync_prefs_.SetPassphraseEncryptionTransitionInProgress(false);
1487 // Call to ClearServerData generates new keystore key on the server. This
1488 // makes keystore bootstrap token invalid. Let's clear it from preferences.
1489 sync_prefs_.SetKeystoreEncryptionBootstrapToken(std::string());
1491 // Shutdown sync, delete the Directory, then restart, restoring the cached
1492 // nigori state.
1493 ShutdownImpl(syncer::DISABLE_SYNC);
1494 startup_controller_->TryStart();
1497 void ProfileSyncService::OnConfigureDone(
1498 const DataTypeManager::ConfigureResult& result) {
1499 configure_status_ = result.status;
1500 data_type_status_table_ = result.data_type_status_table;
1502 if (backend_mode_ != SYNC) {
1503 if (configure_status_ == DataTypeManager::OK) {
1504 StartSyncingWithServer();
1506 // Backup is done after models are associated.
1507 if (backend_mode_ == BACKUP)
1508 backup_finished_ = true;
1510 // Asynchronously check whether sync needs to start.
1511 base::ThreadTaskRunnerHandle::Get()->PostTask(
1512 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1513 startup_controller_weak_factory_.GetWeakPtr()));
1514 } else if (!expect_sync_configuration_aborted_) {
1515 DVLOG(1) << "Backup/rollback backend failed to configure.";
1516 ShutdownImpl(syncer::STOP_SYNC);
1519 return;
1522 // We should have cleared our cached passphrase before we get here (in
1523 // OnBackendInitialized()).
1524 DCHECK(cached_passphrase_.empty());
1526 if (!sync_configure_start_time_.is_null()) {
1527 if (result.status == DataTypeManager::OK) {
1528 base::Time sync_configure_stop_time = base::Time::Now();
1529 base::TimeDelta delta = sync_configure_stop_time -
1530 sync_configure_start_time_;
1531 if (is_first_time_sync_configure_) {
1532 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1533 } else {
1534 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1535 delta);
1538 sync_configure_start_time_ = base::Time();
1541 // Notify listeners that configuration is done.
1542 content::NotificationService::current()->Notify(
1543 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1544 content::Source<ProfileSyncService>(this),
1545 content::NotificationService::NoDetails());
1547 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1548 // The possible status values:
1549 // ABORT - Configuration was aborted. This is not an error, if
1550 // initiated by user.
1551 // OK - Some or all types succeeded.
1552 // Everything else is an UnrecoverableError. So treat it as such.
1554 // First handle the abort case.
1555 if (configure_status_ == DataTypeManager::ABORTED &&
1556 expect_sync_configuration_aborted_) {
1557 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1558 expect_sync_configuration_aborted_ = false;
1559 return;
1562 // Handle unrecoverable error.
1563 if (configure_status_ != DataTypeManager::OK) {
1564 // Something catastrophic had happened. We should only have one
1565 // error representing it.
1566 syncer::SyncError error =
1567 data_type_status_table_.GetUnrecoverableError();
1568 DCHECK(error.IsSet());
1569 std::string message =
1570 "Sync configuration failed with status " +
1571 DataTypeManager::ConfigureStatusToString(configure_status_) +
1572 " caused by " +
1573 syncer::ModelTypeSetToString(
1574 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1575 ": " + error.message();
1576 LOG(ERROR) << "ProfileSyncService error: " << message;
1577 OnInternalUnrecoverableError(error.location(),
1578 message,
1579 true,
1580 ERROR_REASON_CONFIGURATION_FAILURE);
1581 return;
1584 DCHECK_EQ(DataTypeManager::OK, configure_status_);
1586 // We should never get in a state where we have no encrypted datatypes
1587 // enabled, and yet we still think we require a passphrase for decryption.
1588 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1589 !IsEncryptedDatatypeEnabled()));
1591 // This must be done before we start syncing with the server to avoid
1592 // sending unencrypted data up on a first time sync.
1593 if (encryption_pending_)
1594 backend_->EnableEncryptEverything();
1595 NotifyObservers();
1597 if (migrator_.get() &&
1598 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1599 // Migration in progress. Let the migrator know we just finished
1600 // configuring something. It will be up to the migrator to call
1601 // StartSyncingWithServer() if migration is now finished.
1602 migrator_->OnConfigureDone(result);
1603 return;
1606 if (catch_up_configure_in_progress_) {
1607 catch_up_configure_in_progress_ = false;
1608 ClearAndRestartSyncForPassphraseEncryption();
1609 return;
1612 StartSyncingWithServer();
1615 void ProfileSyncService::OnConfigureStart() {
1616 sync_configure_start_time_ = base::Time::Now();
1617 NotifyObservers();
1620 ProfileSyncService::SyncStatusSummary
1621 ProfileSyncService::QuerySyncStatusSummary() {
1622 if (HasUnrecoverableError()) {
1623 return UNRECOVERABLE_ERROR;
1624 } else if (!backend_) {
1625 return NOT_ENABLED;
1626 } else if (backend_mode_ == BACKUP) {
1627 return BACKUP_USER_DATA;
1628 } else if (backend_mode_ == ROLLBACK) {
1629 return ROLLBACK_USER_DATA;
1630 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1631 return SETUP_INCOMPLETE;
1632 } else if (
1633 backend_.get() && HasSyncSetupCompleted() &&
1634 directory_data_type_manager_.get() &&
1635 directory_data_type_manager_->state() == DataTypeManager::STOPPED) {
1636 return DATATYPES_NOT_INITIALIZED;
1637 } else if (IsSyncActive()) {
1638 return INITIALIZED;
1640 return UNKNOWN_ERROR;
1643 std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1644 SyncStatusSummary status = QuerySyncStatusSummary();
1646 std::string config_status_str =
1647 configure_status_ != DataTypeManager::UNKNOWN ?
1648 DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1650 switch (status) {
1651 case UNRECOVERABLE_ERROR:
1652 return "Unrecoverable error detected";
1653 case NOT_ENABLED:
1654 return "Syncing not enabled";
1655 case SETUP_INCOMPLETE:
1656 return "First time sync setup incomplete";
1657 case DATATYPES_NOT_INITIALIZED:
1658 return "Datatypes not fully initialized";
1659 case INITIALIZED:
1660 return "Sync service initialized";
1661 case BACKUP_USER_DATA:
1662 return "Backing-up user data. Status: " + config_status_str;
1663 case ROLLBACK_USER_DATA:
1664 return "Restoring user data. Status: " + config_status_str;
1665 default:
1666 return "Status unknown: Internal error?";
1670 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1671 return startup_controller_->GetBackendInitializationStateString();
1674 bool ProfileSyncService::auto_start_enabled() const {
1675 return startup_controller_->auto_start_enabled();
1678 bool ProfileSyncService::setup_in_progress() const {
1679 return startup_controller_->setup_in_progress();
1682 bool ProfileSyncService::QueryDetailedSyncStatus(
1683 SyncBackendHost::Status* result) {
1684 if (backend_.get() && backend_initialized_) {
1685 *result = backend_->GetDetailedStatus();
1686 return true;
1687 } else {
1688 SyncBackendHost::Status status;
1689 status.sync_protocol_error = last_actionable_error_;
1690 *result = status;
1691 return false;
1695 const AuthError& ProfileSyncService::GetAuthError() const {
1696 return last_auth_error_;
1699 bool ProfileSyncService::FirstSetupInProgress() const {
1700 return !HasSyncSetupCompleted() && startup_controller_->setup_in_progress();
1703 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1704 // This method is a no-op if |setup_in_progress_| remains unchanged.
1705 if (startup_controller_->setup_in_progress() == setup_in_progress)
1706 return;
1708 startup_controller_->set_setup_in_progress(setup_in_progress);
1709 if (!setup_in_progress && backend_initialized())
1710 ReconfigureDatatypeManager();
1711 NotifyObservers();
1714 bool ProfileSyncService::IsSyncAllowed() const {
1715 return IsSyncAllowedByFlag() && !IsManaged();
1718 bool ProfileSyncService::IsSyncActive() const {
1719 return backend_initialized_ && backend_mode_ == SYNC &&
1720 directory_data_type_manager_ &&
1721 directory_data_type_manager_->state() != DataTypeManager::STOPPED;
1724 bool ProfileSyncService::IsSignedIn() const {
1725 // Sync is logged in if there is a non-empty effective account id.
1726 return !signin_->GetAccountIdToUse().empty();
1729 bool ProfileSyncService::backend_initialized() const {
1730 return backend_initialized_;
1733 ProfileSyncService::BackendMode ProfileSyncService::backend_mode() const {
1734 return backend_mode_;
1737 bool ProfileSyncService::ConfigurationDone() const {
1738 return directory_data_type_manager_ &&
1739 directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
1742 bool ProfileSyncService::waiting_for_auth() const {
1743 return is_auth_in_progress_;
1746 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1747 return current_experiments_;
1750 bool ProfileSyncService::HasUnrecoverableError() const {
1751 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1754 bool ProfileSyncService::IsPassphraseRequired() const {
1755 return passphrase_required_reason_ !=
1756 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1759 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1760 // If there is an encrypted datatype enabled and we don't have the proper
1761 // passphrase, we must prompt the user for a passphrase. The only way for the
1762 // user to avoid entering their passphrase is to disable the encrypted types.
1763 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1766 base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1767 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
1768 if (last_synced_time.is_null())
1769 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1771 base::TimeDelta time_since_last_sync = base::Time::Now() - last_synced_time;
1773 if (time_since_last_sync < base::TimeDelta::FromMinutes(1))
1774 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1776 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1777 ui::TimeFormat::LENGTH_SHORT,
1778 time_since_last_sync);
1781 void ProfileSyncService::UpdateSelectedTypesHistogram(
1782 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1783 if (!HasSyncSetupCompleted() ||
1784 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1785 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1788 // Only log the data types that are shown in the sync settings ui.
1789 // Note: the order of these types must match the ordering of
1790 // the respective types in ModelType
1791 const sync_driver::user_selectable_type::UserSelectableSyncType
1792 user_selectable_types[] = {
1793 sync_driver::user_selectable_type::BOOKMARKS,
1794 sync_driver::user_selectable_type::PREFERENCES,
1795 sync_driver::user_selectable_type::PASSWORDS,
1796 sync_driver::user_selectable_type::AUTOFILL,
1797 sync_driver::user_selectable_type::THEMES,
1798 sync_driver::user_selectable_type::TYPED_URLS,
1799 sync_driver::user_selectable_type::EXTENSIONS,
1800 sync_driver::user_selectable_type::APPS,
1801 sync_driver::user_selectable_type::WIFI_CREDENTIAL,
1802 sync_driver::user_selectable_type::PROXY_TABS,
1805 static_assert(36 == syncer::MODEL_TYPE_COUNT,
1806 "custom config histogram must be updated");
1808 if (!sync_everything) {
1809 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1811 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1812 syncer::ModelTypeSet::Iterator it = type_set.First();
1814 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1816 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1817 ++i, it.Inc()) {
1818 const syncer::ModelType type = it.Get();
1819 if (chosen_types.Has(type) &&
1820 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1821 // Selected type has changed - log it.
1822 UMA_HISTOGRAM_ENUMERATION(
1823 "Sync.CustomSync",
1824 user_selectable_types[i],
1825 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1831 #if defined(OS_CHROMEOS)
1832 void ProfileSyncService::RefreshSpareBootstrapToken(
1833 const std::string& passphrase) {
1834 sync_driver::SystemEncryptor encryptor;
1835 syncer::Cryptographer temp_cryptographer(&encryptor);
1836 // The first 2 params (hostname and username) doesn't have any effect here.
1837 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1839 std::string bootstrap_token;
1840 if (!temp_cryptographer.AddKey(key_params)) {
1841 NOTREACHED() << "Failed to add key to cryptographer.";
1843 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1844 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1846 #endif
1848 void ProfileSyncService::OnUserChoseDatatypes(
1849 bool sync_everything,
1850 syncer::ModelTypeSet chosen_types) {
1851 if (!backend_.get() && !HasUnrecoverableError()) {
1852 NOTREACHED();
1853 return;
1856 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1857 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1859 if (directory_data_type_manager_.get())
1860 directory_data_type_manager_->ResetDataTypeErrors();
1861 ChangePreferredDataTypes(chosen_types);
1864 void ProfileSyncService::ChangePreferredDataTypes(
1865 syncer::ModelTypeSet preferred_types) {
1867 DVLOG(1) << "ChangePreferredDataTypes invoked";
1868 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1869 // Will only enable those types that are registered and preferred.
1870 sync_prefs_.SetPreferredDataTypes(registered_types, preferred_types);
1872 // Now reconfigure the DTM.
1873 ReconfigureDatatypeManager();
1875 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1876 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1877 // which types should be enabled and when.
1880 syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1881 if (!IsSyncActive() || !ConfigurationDone())
1882 return syncer::ModelTypeSet();
1883 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1884 const syncer::ModelTypeSet failed_types =
1885 data_type_status_table_.GetFailedTypes();
1886 return Difference(preferred_types, failed_types);
1889 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1890 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1891 const syncer::ModelTypeSet preferred_types =
1892 sync_prefs_.GetPreferredDataTypes(registered_types);
1893 const syncer::ModelTypeSet enforced_types =
1894 Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1895 return Union(preferred_types, enforced_types);
1898 syncer::ModelTypeSet
1899 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1900 const syncer::ModelTypeSet registered_directory_types =
1901 GetRegisteredDirectoryDataTypes();
1902 const syncer::ModelTypeSet preferred_types =
1903 sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1904 const syncer::ModelTypeSet enforced_types =
1905 Intersection(GetDataTypesFromPreferenceProviders(),
1906 registered_directory_types);
1907 return Union(preferred_types, enforced_types);
1910 syncer::ModelTypeSet
1911 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1912 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1915 syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1916 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1917 // we'll need another way to distinguish user-choosable types from
1918 // programmatically-enabled types.
1919 return GetDataTypesFromPreferenceProviders();
1922 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1923 return Union(GetRegisteredDirectoryDataTypes(),
1924 GetRegisteredNonBlockingDataTypes());
1927 syncer::ModelTypeSet
1928 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1929 syncer::ModelTypeSet registered_types;
1930 // The directory_data_type_controllers_ are determined by command-line flags;
1931 // that's effectively what controls the values returned here.
1932 for (DataTypeController::TypeMap::const_iterator it =
1933 directory_data_type_controllers_.begin();
1934 it != directory_data_type_controllers_.end(); ++it) {
1935 registered_types.Put(it->first);
1937 return registered_types;
1940 syncer::ModelTypeSet
1941 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1942 return non_blocking_data_type_manager_.GetRegisteredTypes();
1945 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1946 syncer::PassphraseType passphrase_type = GetPassphraseType();
1947 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1948 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1951 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1952 return backend_->GetPassphraseType();
1955 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1956 return backend_->GetExplicitPassphraseTime();
1959 bool ProfileSyncService::IsCryptographerReady(
1960 const syncer::BaseTransaction* trans) const {
1961 return backend_.get() && backend_->IsCryptographerReady(trans);
1964 void ProfileSyncService::ConfigureDataTypeManager() {
1965 // Don't configure datatypes if the setup UI is still on the screen - this
1966 // is to help multi-screen setting UIs (like iOS) where they don't want to
1967 // start syncing data until the user is done configuring encryption options,
1968 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1969 // SetSetupInProgress(false).
1970 if (backend_mode_ == SYNC && startup_controller_->setup_in_progress())
1971 return;
1973 bool restart = false;
1974 if (!directory_data_type_manager_) {
1975 restart = true;
1976 directory_data_type_manager_.reset(
1977 factory_->CreateDataTypeManager(debug_info_listener_,
1978 &directory_data_type_controllers_,
1979 this,
1980 backend_.get(),
1981 this));
1983 // We create the migrator at the same time.
1984 migrator_.reset(
1985 new browser_sync::BackendMigrator(
1986 profile_->GetDebugName(), GetUserShare(),
1987 this, directory_data_type_manager_.get(),
1988 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1989 base::Unretained(this))));
1992 syncer::ModelTypeSet types;
1993 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1994 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1995 types = syncer::BackupTypes();
1996 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1997 } else {
1998 types = GetPreferredDirectoryDataTypes();
1999 if (!HasSyncSetupCompleted()) {
2000 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
2001 } else if (restart) {
2002 // Datatype downloads on restart are generally due to newly supported
2003 // datatypes (although it's also possible we're picking up where a failed
2004 // previous configuration left off).
2005 // TODO(sync): consider detecting configuration recovery and setting
2006 // the reason here appropriately.
2007 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
2008 } else {
2009 // The user initiated a reconfiguration (either to add or remove types).
2010 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
2014 directory_data_type_manager_->Configure(types, reason);
2017 syncer::UserShare* ProfileSyncService::GetUserShare() const {
2018 if (backend_.get() && backend_initialized_) {
2019 return backend_->GetUserShare();
2021 NOTREACHED();
2022 return NULL;
2025 syncer::sessions::SyncSessionSnapshot
2026 ProfileSyncService::GetLastSessionSnapshot() const {
2027 if (backend_)
2028 return backend_->GetLastSessionSnapshot();
2029 return syncer::sessions::SyncSessionSnapshot();
2032 bool ProfileSyncService::HasUnsyncedItems() const {
2033 if (HasSyncingBackend() && backend_initialized_) {
2034 return backend_->HasUnsyncedItems();
2036 NOTREACHED();
2037 return false;
2040 browser_sync::BackendMigrator*
2041 ProfileSyncService::GetBackendMigratorForTest() {
2042 return migrator_.get();
2045 void ProfileSyncService::GetModelSafeRoutingInfo(
2046 syncer::ModelSafeRoutingInfo* out) const {
2047 if (backend_.get() && backend_initialized_) {
2048 backend_->GetModelSafeRoutingInfo(out);
2049 } else {
2050 NOTREACHED();
2054 base::Value* ProfileSyncService::GetTypeStatusMap() const {
2055 scoped_ptr<base::ListValue> result(new base::ListValue());
2057 if (!backend_.get() || !backend_initialized_) {
2058 return result.release();
2061 DataTypeStatusTable::TypeErrorMap error_map =
2062 data_type_status_table_.GetAllErrors();
2063 ModelTypeSet active_types;
2064 ModelTypeSet passive_types;
2065 ModelSafeRoutingInfo routing_info;
2066 backend_->GetModelSafeRoutingInfo(&routing_info);
2067 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
2068 it != routing_info.end(); ++it) {
2069 if (it->second == syncer::GROUP_PASSIVE) {
2070 passive_types.Put(it->first);
2071 } else {
2072 active_types.Put(it->first);
2076 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
2077 ModelTypeSet &throttled_types(detailed_status.throttled_types);
2078 ModelTypeSet registered = GetRegisteredDataTypes();
2079 scoped_ptr<base::DictionaryValue> type_status_header(
2080 new base::DictionaryValue());
2082 type_status_header->SetString("name", "Model Type");
2083 type_status_header->SetString("status", "header");
2084 type_status_header->SetString("value", "Group Type");
2085 type_status_header->SetString("num_entries", "Total Entries");
2086 type_status_header->SetString("num_live", "Live Entries");
2087 result->Append(type_status_header.release());
2089 scoped_ptr<base::DictionaryValue> type_status;
2090 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2091 ModelType type = it.Get();
2093 type_status.reset(new base::DictionaryValue());
2094 type_status->SetString("name", ModelTypeToString(type));
2096 if (error_map.find(type) != error_map.end()) {
2097 const syncer::SyncError &error = error_map.find(type)->second;
2098 DCHECK(error.IsSet());
2099 switch (error.GetSeverity()) {
2100 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2101 std::string error_text = "Error: " + error.location().ToString() +
2102 ", " + error.GetMessagePrefix() + error.message();
2103 type_status->SetString("status", "error");
2104 type_status->SetString("value", error_text);
2106 break;
2107 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2108 type_status->SetString("status", "disabled");
2109 type_status->SetString("value", error.message());
2110 break;
2111 default:
2112 NOTREACHED() << "Unexpected error severity.";
2113 break;
2115 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2116 // Show a proxy type in "ok" state unless it is disabled by user.
2117 DCHECK(!throttled_types.Has(type));
2118 type_status->SetString("status", "ok");
2119 type_status->SetString("value", "Passive");
2120 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2121 type_status->SetString("status", "warning");
2122 type_status->SetString("value", "Passive, Throttled");
2123 } else if (passive_types.Has(type)) {
2124 type_status->SetString("status", "warning");
2125 type_status->SetString("value", "Passive");
2126 } else if (throttled_types.Has(type)) {
2127 type_status->SetString("status", "warning");
2128 type_status->SetString("value", "Throttled");
2129 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2130 type_status->SetString("status", "ok");
2131 type_status->SetString("value", "Non-Blocking");
2132 } else if (active_types.Has(type)) {
2133 type_status->SetString("status", "ok");
2134 type_status->SetString("value", "Active: " +
2135 ModelSafeGroupToString(routing_info[type]));
2136 } else {
2137 type_status->SetString("status", "warning");
2138 type_status->SetString("value", "Disabled by User");
2141 int live_count = detailed_status.num_entries_by_type[type] -
2142 detailed_status.num_to_delete_entries_by_type[type];
2143 type_status->SetInteger("num_entries",
2144 detailed_status.num_entries_by_type[type]);
2145 type_status->SetInteger("num_live", live_count);
2147 result->Append(type_status.release());
2149 return result.release();
2152 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2153 if (!backend_)
2154 return;
2155 backend_->DeactivateDataType(type);
2158 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2159 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2160 // If the backend isn't running yet, OnBackendInitialized() will call this
2161 // method again after the backend starts up.
2162 if (cached_passphrase_.empty() || !backend_initialized())
2163 return;
2165 // Backend is up and running, so we can consume the cached passphrase.
2166 std::string passphrase = cached_passphrase_;
2167 cached_passphrase_.clear();
2169 // If we need a passphrase to decrypt data, try the cached passphrase.
2170 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2171 if (SetDecryptionPassphrase(passphrase)) {
2172 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2173 return;
2177 // If we get here, we don't have pending keys (or at least, the passphrase
2178 // doesn't decrypt them) - just try to re-encrypt using the encryption
2179 // passphrase.
2180 if (!IsUsingSecondaryPassphrase())
2181 SetEncryptionPassphrase(passphrase, IMPLICIT);
2184 void ProfileSyncService::RequestAccessToken() {
2185 // Only one active request at a time.
2186 if (access_token_request_ != NULL)
2187 return;
2188 request_access_token_retry_timer_.Stop();
2189 OAuth2TokenService::ScopeSet oauth2_scopes;
2190 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2192 // Invalidate previous token, otherwise token service will return the same
2193 // token again.
2194 const std::string& account_id = signin_->GetAccountIdToUse();
2195 if (!access_token_.empty()) {
2196 oauth2_token_service_->InvalidateAccessToken(account_id, oauth2_scopes,
2197 access_token_);
2200 access_token_.clear();
2202 token_request_time_ = base::Time::Now();
2203 token_receive_time_ = base::Time();
2204 next_token_request_time_ = base::Time();
2205 access_token_request_ =
2206 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2209 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2210 PassphraseType type) {
2211 // This should only be called when the backend has been initialized.
2212 DCHECK(backend_initialized());
2213 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2214 "Data is already encrypted using an explicit passphrase";
2215 DCHECK(!(type == EXPLICIT &&
2216 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2217 "Can not set explicit passphrase when decryption is needed.";
2219 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2220 << " passphrase for encryption.";
2221 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2222 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2223 // keys. Hence, as long as we're not trying to do an invalid passphrase
2224 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2225 // will succeed. If for some reason a new encryption key arrives via
2226 // sync later, the SBH will trigger another OnPassphraseRequired().
2227 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2228 NotifyObservers();
2230 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2233 bool ProfileSyncService::SetDecryptionPassphrase(
2234 const std::string& passphrase) {
2235 if (IsPassphraseRequired()) {
2236 DVLOG(1) << "Setting passphrase for decryption.";
2237 bool result = backend_->SetDecryptionPassphrase(passphrase);
2238 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result);
2239 return result;
2240 } else {
2241 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2242 "IsPassphraseRequired() is false.";
2243 return false;
2247 bool ProfileSyncService::EncryptEverythingAllowed() const {
2248 return encrypt_everything_allowed_;
2251 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2252 DCHECK(allowed || !backend_initialized() || !EncryptEverythingEnabled());
2253 encrypt_everything_allowed_ = allowed;
2256 void ProfileSyncService::EnableEncryptEverything() {
2257 DCHECK(EncryptEverythingAllowed());
2259 // Tests override backend_initialized() to always return true, so we
2260 // must check that instead of |backend_initialized_|.
2261 // TODO(akalin): Fix the above. :/
2262 DCHECK(backend_initialized());
2263 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2264 // problems around cancelling encryption in the background (crbug.com/119649).
2265 if (!encrypt_everything_)
2266 encryption_pending_ = true;
2269 bool ProfileSyncService::encryption_pending() const {
2270 // We may be called during the setup process before we're
2271 // initialized (via IsEncryptedDatatypeEnabled and
2272 // IsPassphraseRequiredForDecryption).
2273 return encryption_pending_;
2276 bool ProfileSyncService::EncryptEverythingEnabled() const {
2277 DCHECK(backend_initialized_);
2278 return encrypt_everything_ || encryption_pending_;
2281 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2282 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2283 // We may be called during the setup process before we're
2284 // initialized. In this case, we default to the sensitive types.
2285 return encrypted_types_;
2288 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2289 if (is_sync_managed) {
2290 StopImpl(CLEAR_DATA);
2291 } else {
2292 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2293 startup_controller_->TryStart();
2297 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2298 const std::string& username,
2299 const std::string& password) {
2300 if (IsSyncRequested() && !password.empty()) {
2301 cached_passphrase_ = password;
2302 // Try to consume the passphrase we just cached. If the sync backend
2303 // is not running yet, the passphrase will remain cached until the
2304 // backend starts up.
2305 ConsumeCachedPassphraseIfPossible();
2307 #if defined(OS_CHROMEOS)
2308 RefreshSpareBootstrapToken(password);
2309 #endif
2310 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE) {
2311 // Track the fact that we're still waiting for auth to complete.
2312 is_auth_in_progress_ = true;
2316 void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2317 const std::string& username) {
2318 sync_disabled_by_admin_ = false;
2319 RequestStop(CLEAR_DATA);
2321 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2322 need_backup_ = true;
2323 backup_finished_ = false;
2327 void ProfileSyncService::AddObserver(
2328 sync_driver::SyncServiceObserver* observer) {
2329 observers_.AddObserver(observer);
2332 void ProfileSyncService::RemoveObserver(
2333 sync_driver::SyncServiceObserver* observer) {
2334 observers_.RemoveObserver(observer);
2337 void ProfileSyncService::AddProtocolEventObserver(
2338 browser_sync::ProtocolEventObserver* observer) {
2339 protocol_event_observers_.AddObserver(observer);
2340 if (HasSyncingBackend()) {
2341 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2345 void ProfileSyncService::RemoveProtocolEventObserver(
2346 browser_sync::ProtocolEventObserver* observer) {
2347 protocol_event_observers_.RemoveObserver(observer);
2348 if (HasSyncingBackend() &&
2349 !protocol_event_observers_.might_have_observers()) {
2350 backend_->DisableProtocolEventForwarding();
2354 void ProfileSyncService::AddTypeDebugInfoObserver(
2355 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2356 type_debug_info_observers_.AddObserver(type_debug_info_observer);
2357 if (type_debug_info_observers_.might_have_observers() &&
2358 backend_initialized_) {
2359 backend_->EnableDirectoryTypeDebugInfoForwarding();
2363 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2364 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2365 type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2366 if (!type_debug_info_observers_.might_have_observers() &&
2367 backend_initialized_) {
2368 backend_->DisableDirectoryTypeDebugInfoForwarding();
2372 void ProfileSyncService::AddPreferenceProvider(
2373 SyncTypePreferenceProvider* provider) {
2374 DCHECK(!HasPreferenceProvider(provider))
2375 << "Providers may only be added once!";
2376 preference_providers_.insert(provider);
2379 void ProfileSyncService::RemovePreferenceProvider(
2380 SyncTypePreferenceProvider* provider) {
2381 DCHECK(HasPreferenceProvider(provider))
2382 << "Only providers that have been added before can be removed!";
2383 preference_providers_.erase(provider);
2386 bool ProfileSyncService::HasPreferenceProvider(
2387 SyncTypePreferenceProvider* provider) const {
2388 return preference_providers_.count(provider) > 0;
2391 namespace {
2393 class GetAllNodesRequestHelper
2394 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2395 public:
2396 GetAllNodesRequestHelper(
2397 syncer::ModelTypeSet requested_types,
2398 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2400 void OnReceivedNodesForTypes(
2401 const std::vector<syncer::ModelType>& types,
2402 ScopedVector<base::ListValue> scoped_node_lists);
2404 private:
2405 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2406 virtual ~GetAllNodesRequestHelper();
2408 scoped_ptr<base::ListValue> result_accumulator_;
2410 syncer::ModelTypeSet awaiting_types_;
2411 base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2414 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2415 syncer::ModelTypeSet requested_types,
2416 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2417 : result_accumulator_(new base::ListValue()),
2418 awaiting_types_(requested_types),
2419 callback_(callback) {}
2421 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2422 if (!awaiting_types_.Empty()) {
2423 DLOG(WARNING)
2424 << "GetAllNodesRequest deleted before request was fulfilled. "
2425 << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2429 // Called when the set of nodes for a type or set of types has been returned.
2431 // The nodes for several types can be returned at the same time by specifying
2432 // their types in the |types| array, and putting their results at the
2433 // correspnding indices in the |scoped_node_lists|.
2434 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2435 const std::vector<syncer::ModelType>& types,
2436 ScopedVector<base::ListValue> scoped_node_lists) {
2437 DCHECK_EQ(types.size(), scoped_node_lists.size());
2439 // Take unsafe ownership of the node list.
2440 std::vector<base::ListValue*> node_lists;
2441 scoped_node_lists.release(&node_lists);
2443 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2444 const ModelType type = types[i];
2445 base::ListValue* node_list = node_lists[i];
2447 // Add these results to our list.
2448 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2449 type_dict->SetString("type", ModelTypeToString(type));
2450 type_dict->Set("nodes", node_list);
2451 result_accumulator_->Append(type_dict.release());
2453 // Remember that this part of the request is satisfied.
2454 awaiting_types_.Remove(type);
2457 if (awaiting_types_.Empty()) {
2458 callback_.Run(result_accumulator_.Pass());
2459 callback_.Reset();
2463 } // namespace
2465 void ProfileSyncService::GetAllNodes(
2466 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2467 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2468 directory_types.PutAll(syncer::ControlTypes());
2469 scoped_refptr<GetAllNodesRequestHelper> helper =
2470 new GetAllNodesRequestHelper(directory_types, callback);
2472 if (!backend_initialized_) {
2473 // If there's no backend available to fulfill the request, handle it here.
2474 ScopedVector<base::ListValue> empty_results;
2475 std::vector<ModelType> type_vector;
2476 for (ModelTypeSet::Iterator it = directory_types.First();
2477 it.Good(); it.Inc()) {
2478 type_vector.push_back(it.Get());
2479 empty_results.push_back(new base::ListValue());
2481 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2482 } else {
2483 backend_->GetAllNodesForTypes(
2484 directory_types,
2485 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2489 bool ProfileSyncService::HasObserver(
2490 const sync_driver::SyncServiceObserver* observer) const {
2491 return observers_.HasObserver(observer);
2494 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2495 return sync_js_controller_.AsWeakPtr();
2498 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2499 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2502 // static
2503 bool ProfileSyncService::IsSyncAllowedByFlag() {
2504 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2505 switches::kDisableSync);
2508 bool ProfileSyncService::IsManaged() const {
2509 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2512 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate) {
2513 sync_prefs_.SetSyncRequested(false);
2514 StopImpl(data_fate);
2517 bool ProfileSyncService::IsSyncRequested() const {
2518 return sync_prefs_.IsSyncRequested();
2521 SigninManagerBase* ProfileSyncService::signin() const {
2522 if (!signin_)
2523 return NULL;
2524 return signin_->GetOriginal();
2527 void ProfileSyncService::RequestStart() {
2528 DCHECK(profile_);
2529 sync_prefs_.SetSyncRequested(true);
2530 DCHECK(!signin_.get() || signin_->GetOriginal()->IsAuthenticated());
2531 startup_controller_->TryStart();
2534 void ProfileSyncService::ReconfigureDatatypeManager() {
2535 // If we haven't initialized yet, don't configure the DTM as it could cause
2536 // association to start before a Directory has even been created.
2537 if (backend_initialized_) {
2538 DCHECK(backend_.get());
2539 ConfigureDataTypeManager();
2540 } else if (HasUnrecoverableError()) {
2541 // There is nothing more to configure. So inform the listeners,
2542 NotifyObservers();
2544 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2545 << "Unrecoverable error.";
2546 } else {
2547 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2548 << "initialized";
2552 syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2553 const {
2554 syncer::ModelTypeSet types;
2555 for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2556 preference_providers_.begin();
2557 it != preference_providers_.end();
2558 ++it) {
2559 types.PutAll((*it)->GetPreferredDataTypes());
2561 return types;
2564 const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2565 const {
2566 return data_type_status_table_;
2569 void ProfileSyncService::OnInternalUnrecoverableError(
2570 const tracked_objects::Location& from_here,
2571 const std::string& message,
2572 bool delete_sync_database,
2573 UnrecoverableErrorReason reason) {
2574 DCHECK(!HasUnrecoverableError());
2575 unrecoverable_error_reason_ = reason;
2576 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2579 syncer::SyncManagerFactory::MANAGER_TYPE
2580 ProfileSyncService::GetManagerType() const {
2581 switch (backend_mode_) {
2582 case SYNC:
2583 return syncer::SyncManagerFactory::NORMAL;
2584 case BACKUP:
2585 return syncer::SyncManagerFactory::BACKUP;
2586 case ROLLBACK:
2587 return syncer::SyncManagerFactory::ROLLBACK;
2588 case IDLE:
2589 NOTREACHED();
2591 return syncer::SyncManagerFactory::NORMAL;
2594 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2595 return request_access_token_retry_timer_.IsRunning();
2598 std::string ProfileSyncService::GetAccessTokenForTest() const {
2599 return access_token_;
2602 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2603 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2606 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2607 return sessions_sync_manager_.get();
2610 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2611 return device_info_sync_service_.get();
2614 sync_driver::SyncService::SyncTokenStatus
2615 ProfileSyncService::GetSyncTokenStatus() const {
2616 SyncTokenStatus status;
2617 status.connection_status_update_time = connection_status_update_time_;
2618 status.connection_status = connection_status_;
2619 status.token_request_time = token_request_time_;
2620 status.token_receive_time = token_receive_time_;
2621 status.last_get_token_error = last_get_token_error_;
2622 if (request_access_token_retry_timer_.IsRunning())
2623 status.next_token_request_time = next_token_request_time_;
2624 return status;
2627 void ProfileSyncService::OverrideNetworkResourcesForTest(
2628 scoped_ptr<syncer::NetworkResources> network_resources) {
2629 network_resources_ = network_resources.Pass();
2632 bool ProfileSyncService::HasSyncingBackend() const {
2633 return backend_mode_ != SYNC ? false : backend_ != NULL;
2636 void ProfileSyncService::UpdateFirstSyncTimePref() {
2637 if (!IsSignedIn()) {
2638 // Clear if user's not signed in and rollback is done.
2639 if (backend_mode_ != ROLLBACK)
2640 sync_prefs_.ClearFirstSyncTime();
2641 } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2642 backend_mode_ == SYNC) {
2643 // Set if not set before and it's syncing now.
2644 sync_prefs_.SetFirstSyncTime(base::Time::Now());
2648 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2649 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2650 if (first_sync_time.is_null())
2651 return;
2653 clear_browsing_data_.Run(browsing_data_remover_observer_,
2654 profile_,
2655 first_sync_time,
2656 base::Time::Now());
2659 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2660 BrowsingDataRemover::Observer* observer) {
2661 browsing_data_remover_observer_ = observer;
2664 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2665 base::Callback<void(BrowsingDataRemover::Observer* observer,
2666 Profile*,
2667 base::Time,
2668 base::Time)> c) {
2669 clear_browsing_data_ = c;
2672 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2673 DCHECK_EQ(backend_mode_, SYNC);
2675 #if defined(ENABLE_PRE_SYNC_BACKUP)
2676 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
2677 // Check backup once a day.
2678 if (!last_backup_time_ &&
2679 (last_synced_time.is_null() ||
2680 base::Time::Now() - last_synced_time >=
2681 base::TimeDelta::FromDays(1))) {
2682 // If sync thread is set, need to serialize check on sync thread after
2683 // closing backup DB.
2684 if (sync_thread_) {
2685 sync_thread_->task_runner()->PostTask(
2686 FROM_HERE,
2687 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2688 profile_->GetPath().Append(kSyncBackupDataFolderName),
2689 base::ThreadTaskRunnerHandle::Get(),
2690 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2691 weak_factory_.GetWeakPtr())));
2692 } else {
2693 content::BrowserThread::PostTask(
2694 content::BrowserThread::FILE, FROM_HERE,
2695 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2696 profile_->GetPath().Append(kSyncBackupDataFolderName),
2697 base::ThreadTaskRunnerHandle::Get(),
2698 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2699 weak_factory_.GetWeakPtr())));
2702 #endif
2705 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2706 last_backup_time_.reset(new base::Time(backup_time));
2708 DCHECK(device_info_sync_service_);
2709 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2712 void ProfileSyncService::TryStartSyncAfterBackup() {
2713 startup_controller_->Reset(GetRegisteredDataTypes());
2714 startup_controller_->TryStart();
2717 void ProfileSyncService::CleanUpBackup() {
2718 sync_prefs_.ClearFirstSyncTime();
2719 profile_->GetIOTaskRunner()->PostTask(
2720 FROM_HERE,
2721 base::Bind(base::IgnoreResult(base::DeleteFile),
2722 profile_->GetPath().Append(kSyncBackupDataFolderName),
2723 true));
2726 bool ProfileSyncService::NeedBackup() const {
2727 return need_backup_;
2730 base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2731 return device_info_sync_service_->GetLocalDeviceBackupTime();
2734 void ProfileSyncService::FlushDirectory() const {
2735 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2736 // If sync is not initialized yet, we fail silently.
2737 if (backend_initialized_)
2738 backend_->FlushDirectory();
2741 base::FilePath ProfileSyncService::GetDirectoryPathForTest() const {
2742 return directory_path_;
2745 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2746 if (sync_thread_) {
2747 return sync_thread_->message_loop();
2748 } else if (backend_) {
2749 return backend_->GetSyncLoopForTesting();
2750 } else {
2751 return NULL;
2755 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types) {
2756 if (backend_initialized_)
2757 backend_->RefreshTypesForTest(types);
2760 void ProfileSyncService::RemoveClientFromServer() const {
2761 if (!backend_initialized_) return;
2762 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
2763 std::string birthday;
2764 syncer::UserShare* user_share = GetUserShare();
2765 if (user_share && user_share->directory.get()) {
2766 birthday = user_share->directory->store_birthday();
2768 if (!access_token_.empty() && !cache_guid.empty() && !birthday.empty()) {
2769 sync_stopped_reporter_->ReportSyncStopped(
2770 access_token_, cache_guid, birthday);
2774 void ProfileSyncService::OnMemoryPressure(
2775 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
2776 if (memory_pressure_level ==
2777 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2778 sync_prefs_.SetMemoryPressureWarningCount(
2779 sync_prefs_.GetMemoryPressureWarningCount() + 1);
2783 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2784 int warning_received = sync_prefs_.GetMemoryPressureWarningCount();
2786 if (-1 != warning_received) {
2787 // -1 means it is new client.
2788 if (!sync_prefs_.DidSyncShutdownCleanly()) {
2789 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2790 warning_received);
2791 } else {
2792 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2793 warning_received);
2796 sync_prefs_.SetMemoryPressureWarningCount(0);
2797 // Will set to true during a clean shutdown, so crash or something else will
2798 // remain this as false.
2799 sync_prefs_.SetCleanShutdown(false);
2802 const GURL& ProfileSyncService::sync_service_url() const {
2803 return sync_service_url_;
2806 std::string ProfileSyncService::unrecoverable_error_message() const {
2807 return unrecoverable_error_message_;
2810 tracked_objects::Location ProfileSyncService::unrecoverable_error_location()
2811 const {
2812 return unrecoverable_error_location_;