profile_sync_service.cc revision ab8f6f0bd665d3c1ff476eb06c58c42630e462d4
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.
4
5#include "chrome/browser/sync/profile_sync_service.h"
6
7#include <cstddef>
8#include <map>
9#include <vector>
10
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/message_loop/message_loop.h"
21#include "base/metrics/histogram.h"
22#include "base/strings/string16.h"
23#include "base/strings/stringprintf.h"
24#include "base/threading/thread_restrictions.h"
25#include "build/build_config.h"
26#include "chrome/browser/bookmarks/enhanced_bookmarks_features.h"
27#include "chrome/browser/browser_process.h"
28#include "chrome/browser/browsing_data/browsing_data_helper.h"
29#include "chrome/browser/chrome_notification_types.h"
30#include "chrome/browser/defaults.h"
31#include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
32#include "chrome/browser/net/chrome_cookie_notification_details.h"
33#include "chrome/browser/password_manager/password_store_factory.h"
34#include "chrome/browser/prefs/chrome_pref_service_factory.h"
35#include "chrome/browser/prefs/pref_service_syncable.h"
36#include "chrome/browser/profiles/profile.h"
37#include "chrome/browser/services/gcm/gcm_profile_service.h"
38#include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
39#include "chrome/browser/signin/about_signin_internals_factory.h"
40#include "chrome/browser/signin/chrome_signin_client_factory.h"
41#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
42#include "chrome/browser/signin/signin_manager_factory.h"
43#include "chrome/browser/sync/backend_migrator.h"
44#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
45#include "chrome/browser/sync/glue/favicon_cache.h"
46#include "chrome/browser/sync/glue/sync_backend_host.h"
47#include "chrome/browser/sync/glue/sync_backend_host_impl.h"
48#include "chrome/browser/sync/glue/sync_start_util.h"
49#include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
50#include "chrome/browser/sync/profile_sync_components_factory_impl.h"
51#include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
52#include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
53#include "chrome/browser/sync/sync_error_controller.h"
54#include "chrome/browser/sync/sync_type_preference_provider.h"
55#include "chrome/browser/ui/browser.h"
56#include "chrome/browser/ui/browser_list.h"
57#include "chrome/browser/ui/browser_window.h"
58#include "chrome/browser/ui/global_error/global_error_service.h"
59#include "chrome/browser/ui/global_error/global_error_service_factory.h"
60#include "chrome/common/chrome_switches.h"
61#include "chrome/common/chrome_version_info.h"
62#include "chrome/common/pref_names.h"
63#include "chrome/common/url_constants.h"
64#include "chrome/grit/generated_resources.h"
65#include "components/gcm_driver/gcm_driver.h"
66#include "components/invalidation/invalidation_service.h"
67#include "components/invalidation/profile_invalidation_provider.h"
68#include "components/password_manager/core/browser/password_store.h"
69#include "components/pref_registry/pref_registry_syncable.h"
70#include "components/signin/core/browser/about_signin_internals.h"
71#include "components/signin/core/browser/profile_oauth2_token_service.h"
72#include "components/signin/core/browser/signin_manager.h"
73#include "components/signin/core/browser/signin_metrics.h"
74#include "components/sync_driver/change_processor.h"
75#include "components/sync_driver/data_type_controller.h"
76#include "components/sync_driver/device_info.h"
77#include "components/sync_driver/pref_names.h"
78#include "components/sync_driver/system_encryptor.h"
79#include "components/sync_driver/user_selectable_sync_type.h"
80#include "content/public/browser/browser_thread.h"
81#include "content/public/browser/notification_details.h"
82#include "content/public/browser/notification_service.h"
83#include "content/public/browser/notification_source.h"
84#include "net/cookies/cookie_monster.h"
85#include "net/url_request/url_request_context_getter.h"
86#include "sync/api/sync_error.h"
87#include "sync/internal_api/public/configure_reason.h"
88#include "sync/internal_api/public/http_bridge_network_resources.h"
89#include "sync/internal_api/public/network_resources.h"
90#include "sync/internal_api/public/sessions/type_debug_info_observer.h"
91#include "sync/internal_api/public/shutdown_reason.h"
92#include "sync/internal_api/public/sync_context_proxy.h"
93#include "sync/internal_api/public/sync_encryption_handler.h"
94#include "sync/internal_api/public/util/experiments.h"
95#include "sync/internal_api/public/util/sync_db_util.h"
96#include "sync/internal_api/public/util/sync_string_conversions.h"
97#include "sync/js/js_event_details.h"
98#include "sync/util/cryptographer.h"
99#include "ui/base/l10n/l10n_util.h"
100#include "ui/base/l10n/time_format.h"
101
102#if defined(OS_ANDROID)
103#include "sync/internal_api/public/read_transaction.h"
104#endif
105
106using browser_sync::NotificationServiceSessionsRouter;
107using browser_sync::ProfileSyncServiceStartBehavior;
108using browser_sync::SessionsSyncManager;
109using browser_sync::SyncBackendHost;
110using sync_driver::ChangeProcessor;
111using sync_driver::DataTypeController;
112using sync_driver::DataTypeManager;
113using sync_driver::DataTypeStatusTable;
114using sync_driver::DeviceInfoSyncService;
115using syncer::ModelType;
116using syncer::ModelTypeSet;
117using syncer::JsBackend;
118using syncer::JsController;
119using syncer::JsEventDetails;
120using syncer::JsEventHandler;
121using syncer::ModelSafeRoutingInfo;
122using syncer::SyncCredentials;
123using syncer::SyncProtocolError;
124using syncer::WeakHandle;
125
126typedef GoogleServiceAuthError AuthError;
127
128const char* ProfileSyncService::kSyncServerUrl =
129    "https://clients4.google.com/chrome-sync";
130
131const char* ProfileSyncService::kDevServerUrl =
132    "https://clients4.google.com/chrome-sync/dev";
133
134const char kSyncUnrecoverableErrorHistogram[] =
135    "Sync.UnrecoverableErrors";
136
137const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
138  // Number of initial errors (in sequence) to ignore before applying
139  // exponential back-off rules.
140  0,
141
142  // Initial delay for exponential back-off in ms.
143  2000,
144
145  // Factor by which the waiting time will be multiplied.
146  2,
147
148  // Fuzzing percentage. ex: 10% will spread requests randomly
149  // between 90%-100% of the calculated time.
150  0.2, // 20%
151
152  // Maximum amount of time we are willing to delay our request in ms.
153  // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
154  // RequestAccessToken on connection state change after backoff
155  1000 * 3600 * 4, // 4 hours.
156
157  // Time to keep an entry from being discarded even when it
158  // has no significant state, -1 to never discard.
159  -1,
160
161  // Don't use initial delay unless the last request was an error.
162  false,
163};
164
165static const base::FilePath::CharType kSyncDataFolderName[] =
166    FILE_PATH_LITERAL("Sync Data");
167
168static const base::FilePath::CharType kSyncBackupDataFolderName[] =
169    FILE_PATH_LITERAL("Sync Data Backup");
170
171namespace {
172
173void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
174                       Profile* profile,
175                       base::Time start,
176                       base::Time end) {
177  // BrowsingDataRemover deletes itself when it's done.
178  BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
179      profile, start, end);
180  if (observer)
181    remover->AddObserver(observer);
182  remover->Remove(BrowsingDataRemover::REMOVE_ALL,
183                  BrowsingDataHelper::ALL);
184
185  scoped_refptr<password_manager::PasswordStore> password =
186      PasswordStoreFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS);
187  password->RemoveLoginsSyncedBetween(start, end);
188}
189
190}  // anonymous namespace
191
192bool ShouldShowActionOnUI(
193    const syncer::SyncProtocolError& error) {
194  return (error.action != syncer::UNKNOWN_ACTION &&
195          error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
196          error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
197}
198
199ProfileSyncService::ProfileSyncService(
200    scoped_ptr<ProfileSyncComponentsFactory> factory,
201    Profile* profile,
202    scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
203    ProfileOAuth2TokenService* oauth2_token_service,
204    ProfileSyncServiceStartBehavior start_behavior)
205    : OAuth2TokenService::Consumer("sync"),
206      last_auth_error_(AuthError::AuthErrorNone()),
207      passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
208      factory_(factory.Pass()),
209      profile_(profile),
210      sync_prefs_(profile_->GetPrefs()),
211      sync_service_url_(GetSyncServiceURL(*CommandLine::ForCurrentProcess())),
212      is_first_time_sync_configure_(false),
213      backend_initialized_(false),
214      sync_disabled_by_admin_(false),
215      is_auth_in_progress_(false),
216      signin_(signin_wrapper.Pass()),
217      unrecoverable_error_reason_(ERROR_REASON_UNSET),
218      expect_sync_configuration_aborted_(false),
219      encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
220      encrypt_everything_allowed_(true),
221      encrypt_everything_(false),
222      encryption_pending_(false),
223      configure_status_(DataTypeManager::UNKNOWN),
224      oauth2_token_service_(oauth2_token_service),
225      request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
226      weak_factory_(this),
227      startup_controller_weak_factory_(this),
228      connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
229      last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
230      network_resources_(new syncer::HttpBridgeNetworkResources),
231      startup_controller_(
232          start_behavior,
233          oauth2_token_service,
234          &sync_prefs_,
235          signin_.get(),
236          base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
237                     startup_controller_weak_factory_.GetWeakPtr(),
238                     SYNC)),
239      backup_rollback_controller_(
240          &sync_prefs_,
241          signin_.get(),
242          base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
243                     startup_controller_weak_factory_.GetWeakPtr(),
244                     BACKUP),
245          base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
246                     startup_controller_weak_factory_.GetWeakPtr(),
247                     ROLLBACK)),
248      backend_mode_(IDLE),
249      need_backup_(false),
250      backup_finished_(false),
251      clear_browsing_data_(base::Bind(&ClearBrowsingData)),
252      browsing_data_remover_observer_(NULL) {
253  DCHECK(profile);
254  syncer::SyncableService::StartSyncFlare flare(
255      sync_start_util::GetFlareForSyncableService(profile->GetPath()));
256  scoped_ptr<browser_sync::LocalSessionEventRouter> router(
257      new NotificationServiceSessionsRouter(profile, flare));
258
259  DCHECK(factory_.get());
260  local_device_ = factory_->CreateLocalDeviceInfoProvider();
261  sessions_sync_manager_.reset(
262      new SessionsSyncManager(profile, local_device_.get(), router.Pass()));
263  device_info_sync_service_.reset(
264      new DeviceInfoSyncService(local_device_.get()));
265}
266
267ProfileSyncService::~ProfileSyncService() {
268  sync_prefs_.RemoveSyncPrefObserver(this);
269  // Shutdown() should have been called before destruction.
270  CHECK(!backend_initialized_);
271}
272
273bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
274  // Exit if sync is disabled.
275  if (IsManaged() || sync_prefs_.IsStartSuppressed())
276    return false;
277
278  // Sync is logged in if there is a non-empty effective username.
279  return !signin_->GetEffectiveUsername().empty();
280}
281
282bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
283  if (!oauth2_token_service_)
284    return false;
285
286  return oauth2_token_service_->RefreshTokenIsAvailable(
287      signin_->GetAccountIdToUse());
288}
289
290void ProfileSyncService::Initialize() {
291  // We clear this here (vs Shutdown) because we want to remember that an error
292  // happened on shutdown so we can display details (message, location) about it
293  // in about:sync.
294  ClearStaleErrors();
295
296  sync_prefs_.AddSyncPrefObserver(this);
297
298  // For now, the only thing we can do through policy is to turn sync off.
299  if (IsManaged()) {
300    DisableForUser();
301    return;
302  }
303
304  RegisterAuthNotifications();
305
306  if (!HasSyncSetupCompleted() || signin_->GetEffectiveUsername().empty()) {
307    // Clean up in case of previous crash / setup abort / signout.
308    DisableForUser();
309  }
310
311  TrySyncDatatypePrefRecovery();
312
313  last_synced_time_ = sync_prefs_.GetLastSyncedTime();
314
315#if defined(OS_CHROMEOS)
316  std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
317  if (bootstrap_token.empty()) {
318    sync_prefs_.SetEncryptionBootstrapToken(
319        sync_prefs_.GetSpareBootstrapToken());
320  }
321#endif
322
323#if !defined(OS_ANDROID)
324  DCHECK(sync_error_controller_ == NULL)
325      << "Initialize() called more than once.";
326  sync_error_controller_.reset(new SyncErrorController(this));
327  AddObserver(sync_error_controller_.get());
328#endif
329
330  bool running_rollback = false;
331  if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
332    // Backup is needed if user's not signed in or signed in but previous
333    // backup didn't finish, i.e. backend didn't switch from backup to sync.
334    need_backup_ = signin_->GetEffectiveUsername().empty() ||
335        sync_prefs_.GetFirstSyncTime().is_null();
336
337    // Try to resume rollback if it didn't finish in last session.
338    running_rollback = backup_rollback_controller_.StartRollback();
339  } else {
340    need_backup_ = false;
341  }
342
343#if defined(ENABLE_PRE_SYNC_BACKUP)
344  if (!running_rollback && signin_->GetEffectiveUsername().empty()) {
345    CleanUpBackup();
346  }
347#else
348  DCHECK(!running_rollback);
349#endif
350
351  startup_controller_.Reset(GetRegisteredDataTypes());
352  startup_controller_.TryStart();
353}
354
355void ProfileSyncService::TrySyncDatatypePrefRecovery() {
356  DCHECK(!sync_initialized());
357  if (!HasSyncSetupCompleted())
358    return;
359
360  // There was a bug where OnUserChoseDatatypes was not properly called on
361  // configuration (see crbug.com/154940). We detect this by checking whether
362  // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
363  // completed, it means sync was not properly configured, so we manually
364  // set kSyncKeepEverythingSynced.
365  PrefService* const pref_service = profile_->GetPrefs();
366  if (!pref_service)
367    return;
368  if (GetPreferredDataTypes().Size() > 1)
369    return;
370
371  const PrefService::Preference* keep_everything_synced =
372      pref_service->FindPreference(
373          sync_driver::prefs::kSyncKeepEverythingSynced);
374  // This will be false if the preference was properly set or if it's controlled
375  // by policy.
376  if (!keep_everything_synced->IsDefaultValue())
377    return;
378
379  // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
380  // types now, before we configure.
381  UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
382  sync_prefs_.SetKeepEverythingSynced(true);
383  syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
384}
385
386void ProfileSyncService::StartSyncingWithServer() {
387  if (backend_)
388    backend_->StartSyncingWithServer();
389}
390
391void ProfileSyncService::RegisterAuthNotifications() {
392  oauth2_token_service_->AddObserver(this);
393  if (signin())
394    signin()->AddObserver(this);
395}
396
397void ProfileSyncService::UnregisterAuthNotifications() {
398  if (signin())
399    signin()->RemoveObserver(this);
400  oauth2_token_service_->RemoveObserver(this);
401}
402
403void ProfileSyncService::RegisterDataTypeController(
404    DataTypeController* data_type_controller) {
405  DCHECK_EQ(
406      directory_data_type_controllers_.count(data_type_controller->type()),
407      0U);
408  DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
409      data_type_controller->type()));
410  directory_data_type_controllers_[data_type_controller->type()] =
411      data_type_controller;
412}
413
414void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
415  DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
416      << "Duplicate registration of type " << ModelTypeToString(type);
417
418  // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
419  // fixed and we have some way of telling whether or not this type should be
420  // enabled.
421  non_blocking_data_type_manager_.RegisterType(type, false);
422}
423
424void ProfileSyncService::InitializeNonBlockingType(
425    syncer::ModelType type,
426    const scoped_refptr<base::SequencedTaskRunner>& task_runner,
427    const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) {
428  non_blocking_data_type_manager_.InitializeType(
429      type, task_runner, type_sync_proxy);
430}
431
432bool ProfileSyncService::IsDataTypeControllerRunning(
433    syncer::ModelType type) const {
434  DataTypeController::TypeMap::const_iterator iter =
435      directory_data_type_controllers_.find(type);
436  if (iter == directory_data_type_controllers_.end()) {
437    return false;
438  }
439  return iter->second->state() == DataTypeController::RUNNING;
440}
441
442browser_sync::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
443  if (!IsDataTypeControllerRunning(syncer::SESSIONS))
444    return NULL;
445  return sessions_sync_manager_.get();
446}
447
448browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
449  return sessions_sync_manager_->GetFaviconCache();
450}
451
452browser_sync::SyncedWindowDelegatesGetter*
453ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
454  return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
455}
456
457sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
458    const {
459  if (!IsDataTypeControllerRunning(syncer::DEVICE_INFO))
460    return NULL;
461
462  return device_info_sync_service_.get();
463}
464
465sync_driver::LocalDeviceInfoProvider*
466ProfileSyncService::GetLocalDeviceInfoProvider() {
467  return local_device_.get();
468}
469
470void ProfileSyncService::GetDataTypeControllerStates(
471  DataTypeController::StateMap* state_map) const {
472    for (DataTypeController::TypeMap::const_iterator iter =
473         directory_data_type_controllers_.begin();
474         iter != directory_data_type_controllers_.end();
475         ++iter)
476      (*state_map)[iter->first] = iter->second.get()->state();
477}
478
479SyncCredentials ProfileSyncService::GetCredentials() {
480  SyncCredentials credentials;
481  if (backend_mode_ == SYNC) {
482    credentials.email = signin_->GetEffectiveUsername();
483    DCHECK(!credentials.email.empty());
484    credentials.sync_token = access_token_;
485
486    if (credentials.sync_token.empty())
487      credentials.sync_token = "credentials_lost";
488
489    credentials.scope_set.insert(signin_->GetSyncScopeToUse());
490  }
491
492  return credentials;
493}
494
495bool ProfileSyncService::ShouldDeleteSyncFolder() {
496  switch (backend_mode_) {
497    case SYNC:
498      return !HasSyncSetupCompleted();
499    case BACKUP:
500      return true;
501    case ROLLBACK:
502      return false;
503    case IDLE:
504      NOTREACHED();
505      return true;
506  }
507  return true;
508}
509
510void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
511  if (!backend_) {
512    NOTREACHED();
513    return;
514  }
515
516  SyncCredentials credentials = GetCredentials();
517
518  scoped_refptr<net::URLRequestContextGetter> request_context_getter(
519      profile_->GetRequestContext());
520
521  if (backend_mode_ == SYNC && delete_stale_data)
522    ClearStaleErrors();
523
524  scoped_ptr<syncer::UnrecoverableErrorHandler>
525      backend_unrecoverable_error_handler(
526          new browser_sync::BackendUnrecoverableErrorHandler(
527              MakeWeakHandle(weak_factory_.GetWeakPtr())));
528
529  backend_->Initialize(
530      this,
531      sync_thread_.Pass(),
532      GetJsEventHandler(),
533      sync_service_url_,
534      credentials,
535      delete_stale_data,
536      scoped_ptr<syncer::SyncManagerFactory>(
537          new syncer::SyncManagerFactory(GetManagerType())).Pass(),
538      backend_unrecoverable_error_handler.Pass(),
539      &browser_sync::ChromeReportUnrecoverableError,
540      network_resources_.get());
541}
542
543bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
544  if (encryption_pending())
545    return true;
546  const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
547  const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
548  DCHECK(encrypted_types.Has(syncer::PASSWORDS));
549  return !Intersection(preferred_types, encrypted_types).Empty();
550}
551
552void ProfileSyncService::OnSyncConfigureRetry() {
553  // Note: in order to handle auth failures that arise before the backend is
554  // initialized (e.g. from invalidation notifier, or downloading new control
555  // types), we have to gracefully handle configuration retries at all times.
556  // At this point an auth error badge should be shown, which once resolved
557  // will trigger a new sync cycle.
558  NotifyObservers();
559}
560
561void ProfileSyncService::OnProtocolEvent(
562    const syncer::ProtocolEvent& event) {
563  FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
564                    protocol_event_observers_,
565                    OnProtocolEvent(event));
566}
567
568void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
569    syncer::ModelType type,
570    const syncer::CommitCounters& counters) {
571  FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
572                    type_debug_info_observers_,
573                    OnCommitCountersUpdated(type, counters));
574}
575
576void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
577    syncer::ModelType type,
578    const syncer::UpdateCounters& counters) {
579  FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
580                    type_debug_info_observers_,
581                    OnUpdateCountersUpdated(type, counters));
582}
583
584void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
585    syncer::ModelType type,
586    const syncer::StatusCounters& counters) {
587  FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
588                    type_debug_info_observers_,
589                    OnStatusCountersUpdated(type, counters));
590}
591
592void ProfileSyncService::OnDataTypeRequestsSyncStartup(
593    syncer::ModelType type) {
594  DCHECK(syncer::UserTypes().Has(type));
595  if (backend_.get()) {
596    DVLOG(1) << "A data type requested sync startup, but it looks like "
597                "something else beat it to the punch.";
598    return;
599  }
600
601  if (!GetPreferredDataTypes().Has(type)) {
602    // We can get here as datatype SyncableServices are typically wired up
603    // to the native datatype even if sync isn't enabled.
604    DVLOG(1) << "Dropping sync startup request because type "
605             << syncer::ModelTypeToString(type) << "not enabled.";
606    return;
607  }
608
609  startup_controller_.OnDataTypeRequestsSyncStartup(type);
610}
611
612void ProfileSyncService::StartUpSlowBackendComponents(
613    ProfileSyncService::BackendMode mode) {
614  DCHECK_NE(IDLE, mode);
615  if (backend_mode_ == mode) {
616    return;
617  }
618
619  // Backend mode transition rules:
620  // * can transit from IDLE to any other non-IDLE mode.
621  // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
622  //   be explicitly shut down before backup/rollback starts.
623  // * can not transit out of ROLLBACK mode until rollback is finished
624  //   (successfully or unsuccessfully).
625  // * can not transit out of BACKUP mode until backup is finished
626  //   (successfully or unsuccessfully).
627  // * if backup is needed, can only transit to SYNC if backup is finished,
628
629  if (backend_mode_ == SYNC) {
630    LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
631    return;
632  }
633
634  if (backend_mode_ == ROLLBACK ||
635      (backend_mode_ == BACKUP && !backup_finished_)) {
636    // Wait for rollback/backup to finish before start new backend.
637    return;
638  }
639
640  if (mode == SYNC && NeedBackup() && !backup_finished_) {
641    if (backend_mode_ != BACKUP)
642      backup_rollback_controller_.StartBackup();
643    return;
644  }
645
646  DVLOG(1) << "Start backend mode: " << mode;
647
648  if (backend_) {
649    if (mode == SYNC)
650      ShutdownImpl(syncer::SWITCH_MODE_SYNC);
651    else
652      ShutdownImpl(syncer::STOP_SYNC);
653  }
654
655  backend_mode_ = mode;
656
657  if (backend_mode_ == BACKUP)
658    backup_start_time_ = base::Time::Now();
659
660  if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
661    UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
662                               base::Time::Now() - backup_start_time_);
663    backup_start_time_ = base::Time();
664  }
665
666  if (backend_mode_ == ROLLBACK)
667    ClearBrowsingDataSinceFirstSync();
668  else if (backend_mode_ == SYNC)
669    CheckSyncBackupIfNeeded();
670
671  base::FilePath sync_folder = backend_mode_ == SYNC ?
672      base::FilePath(kSyncDataFolderName) :
673      base::FilePath(kSyncBackupDataFolderName);
674
675  invalidation::InvalidationService* invalidator = NULL;
676  if (backend_mode_ == SYNC) {
677    invalidation::ProfileInvalidationProvider* provider =
678        invalidation::ProfileInvalidationProviderFactory::GetForProfile(
679            profile_);
680    if (provider)
681      invalidator = provider->GetInvalidationService();
682  }
683
684  backend_.reset(
685      factory_->CreateSyncBackendHost(
686          profile_->GetDebugName(),
687          profile_,
688          invalidator,
689          sync_prefs_.AsWeakPtr(),
690          sync_folder));
691
692  // Initialize the backend.  Every time we start up a new SyncBackendHost,
693  // we'll want to start from a fresh SyncDB, so delete any old one that might
694  // be there.
695  InitializeBackend(ShouldDeleteSyncFolder());
696
697  UpdateFirstSyncTimePref();
698
699  NotifyObservers();
700}
701
702void ProfileSyncService::OnGetTokenSuccess(
703    const OAuth2TokenService::Request* request,
704    const std::string& access_token,
705    const base::Time& expiration_time) {
706  DCHECK_EQ(access_token_request_, request);
707  access_token_request_.reset();
708  access_token_ = access_token;
709  token_receive_time_ = base::Time::Now();
710  last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
711
712  if (sync_prefs_.SyncHasAuthError()) {
713    sync_prefs_.SetSyncAuthError(false);
714    UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
715                              AUTH_ERROR_FIXED,
716                              AUTH_ERROR_LIMIT);
717  }
718
719  if (HasSyncingBackend())
720    backend_->UpdateCredentials(GetCredentials());
721  else
722    startup_controller_.TryStart();
723}
724
725void ProfileSyncService::OnGetTokenFailure(
726    const OAuth2TokenService::Request* request,
727    const GoogleServiceAuthError& error) {
728  DCHECK_EQ(access_token_request_, request);
729  DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
730  access_token_request_.reset();
731  last_get_token_error_ = error;
732  switch (error.state()) {
733    case GoogleServiceAuthError::CONNECTION_FAILED:
734    case GoogleServiceAuthError::REQUEST_CANCELED:
735    case GoogleServiceAuthError::SERVICE_ERROR:
736    case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
737      // Transient error. Retry after some time.
738      request_access_token_backoff_.InformOfRequest(false);
739      next_token_request_time_ = base::Time::Now() +
740          request_access_token_backoff_.GetTimeUntilRelease();
741      request_access_token_retry_timer_.Start(
742            FROM_HERE,
743            request_access_token_backoff_.GetTimeUntilRelease(),
744            base::Bind(&ProfileSyncService::RequestAccessToken,
745                        weak_factory_.GetWeakPtr()));
746      NotifyObservers();
747      break;
748    }
749    case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
750      if (!sync_prefs_.SyncHasAuthError()) {
751        sync_prefs_.SetSyncAuthError(true);
752        UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
753                                  AUTH_ERROR_ENCOUNTERED,
754                                  AUTH_ERROR_LIMIT);
755      }
756      // Fallthrough.
757    }
758    default: {
759      if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
760        LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
761      }
762      // Show error to user.
763      UpdateAuthErrorState(error);
764    }
765  }
766}
767
768void ProfileSyncService::OnRefreshTokenAvailable(
769    const std::string& account_id) {
770  if (account_id == signin_->GetAccountIdToUse())
771    OnRefreshTokensLoaded();
772}
773
774void ProfileSyncService::OnRefreshTokenRevoked(
775    const std::string& account_id) {
776  if (!IsOAuthRefreshTokenAvailable()) {
777    access_token_.clear();
778    // The additional check around IsOAuthRefreshTokenAvailable() above
779    // prevents us sounding the alarm if we actually have a valid token but
780    // a refresh attempt failed for any variety of reasons
781    // (e.g. flaky network). It's possible the token we do have is also
782    // invalid, but in that case we should already have (or can expect) an
783    // auth error sent from the sync backend.
784    UpdateAuthErrorState(
785        GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
786  }
787}
788
789void ProfileSyncService::OnRefreshTokensLoaded() {
790  // This notification gets fired when OAuth2TokenService loads the tokens
791  // from storage.
792  // Initialize the backend if sync is enabled. If the sync token was
793  // not loaded, GetCredentials() will generate invalid credentials to
794  // cause the backend to generate an auth error (crbug.com/121755).
795  if (HasSyncingBackend()) {
796    RequestAccessToken();
797  } else {
798    startup_controller_.TryStart();
799  }
800}
801
802void ProfileSyncService::Shutdown() {
803  UnregisterAuthNotifications();
804
805  ShutdownImpl(syncer::BROWSER_SHUTDOWN);
806  if (sync_error_controller_) {
807    // Destroy the SyncErrorController when the service shuts down for good.
808    RemoveObserver(sync_error_controller_.get());
809    sync_error_controller_.reset();
810  }
811
812  if (sync_thread_)
813    sync_thread_->Stop();
814}
815
816void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
817  if (!backend_)
818    return;
819
820  non_blocking_data_type_manager_.DisconnectSyncBackend();
821
822  // First, we spin down the backend to stop change processing as soon as
823  // possible.
824  base::Time shutdown_start_time = base::Time::Now();
825  backend_->StopSyncingForShutdown();
826
827  // Stop all data type controllers, if needed.  Note that until Stop
828  // completes, it is possible in theory to have a ChangeProcessor apply a
829  // change from a native model.  In that case, it will get applied to the sync
830  // database (which doesn't get destroyed until we destroy the backend below)
831  // as an unsynced change.  That will be persisted, and committed on restart.
832  if (directory_data_type_manager_) {
833    if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
834      // When aborting as part of shutdown, we should expect an aborted sync
835      // configure result, else we'll dcheck when we try to read the sync error.
836      expect_sync_configuration_aborted_ = true;
837      directory_data_type_manager_->Stop();
838    }
839    directory_data_type_manager_.reset();
840  }
841
842  // Shutdown the migrator before the backend to ensure it doesn't pull a null
843  // snapshot.
844  migrator_.reset();
845  sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
846
847  // Move aside the backend so nobody else tries to use it while we are
848  // shutting it down.
849  scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
850  if (doomed_backend) {
851    sync_thread_ = doomed_backend->Shutdown(reason);
852    doomed_backend.reset();
853  }
854  base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
855  UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
856
857  weak_factory_.InvalidateWeakPtrs();
858
859  if (backend_mode_ == SYNC)
860    startup_controller_.Reset(GetRegisteredDataTypes());
861
862  // Don't let backup block sync regardless backup succeeded or not.
863  if (backend_mode_ == BACKUP)
864    backup_finished_ = true;
865
866  // Sync could be blocked by rollback/backup. Post task to check whether sync
867  // should start after shutting down rollback/backup backend.
868  if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
869      reason != syncer::SWITCH_MODE_SYNC &&
870      reason != syncer::BROWSER_SHUTDOWN) {
871    base::MessageLoop::current()->PostTask(
872        FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
873                              startup_controller_weak_factory_.GetWeakPtr()));
874  }
875
876  // Clear various flags.
877  backend_mode_ = IDLE;
878  expect_sync_configuration_aborted_ = false;
879  is_auth_in_progress_ = false;
880  backend_initialized_ = false;
881  cached_passphrase_.clear();
882  access_token_.clear();
883  encryption_pending_ = false;
884  encrypt_everything_ = false;
885  encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
886  passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
887  request_access_token_retry_timer_.Stop();
888  // Revert to "no auth error".
889  if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
890    UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
891
892  NotifyObservers();
893}
894
895void ProfileSyncService::DisableForUser() {
896  // Clear prefs (including SyncSetupHasCompleted) before shutting down so
897  // PSS clients don't think we're set up while we're shutting down.
898  sync_prefs_.ClearPreferences();
899  ClearUnrecoverableError();
900  ShutdownImpl(syncer::DISABLE_SYNC);
901}
902
903bool ProfileSyncService::HasSyncSetupCompleted() const {
904  return sync_prefs_.HasSyncSetupCompleted();
905}
906
907void ProfileSyncService::SetSyncSetupCompleted() {
908  sync_prefs_.SetSyncSetupCompleted();
909}
910
911void ProfileSyncService::UpdateLastSyncedTime() {
912  last_synced_time_ = base::Time::Now();
913  sync_prefs_.SetLastSyncedTime(last_synced_time_);
914}
915
916void ProfileSyncService::NotifyObservers() {
917  FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
918                    OnStateChanged());
919}
920
921void ProfileSyncService::NotifySyncCycleCompleted() {
922  FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
923                    OnSyncCycleCompleted());
924}
925
926void ProfileSyncService::ClearStaleErrors() {
927  ClearUnrecoverableError();
928  last_actionable_error_ = SyncProtocolError();
929  // Clear the data type errors as well.
930  if (directory_data_type_manager_.get())
931    directory_data_type_manager_->ResetDataTypeErrors();
932
933}
934
935void ProfileSyncService::ClearUnrecoverableError() {
936  unrecoverable_error_reason_ = ERROR_REASON_UNSET;
937  unrecoverable_error_message_.clear();
938  unrecoverable_error_location_ = tracked_objects::Location();
939}
940
941void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) {
942  if (directory_data_type_controllers_.count(data_type) > 0)
943    return;
944  NOTREACHED();
945}
946
947// An invariant has been violated.  Transition to an error state where we try
948// to do as little work as possible, to avoid further corruption or crashes.
949void ProfileSyncService::OnUnrecoverableError(
950    const tracked_objects::Location& from_here,
951    const std::string& message) {
952  // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
953  // interface are assumed to originate within the syncer.
954  unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
955  OnUnrecoverableErrorImpl(from_here, message, true);
956}
957
958void ProfileSyncService::OnUnrecoverableErrorImpl(
959    const tracked_objects::Location& from_here,
960    const std::string& message,
961    bool delete_sync_database) {
962  DCHECK(HasUnrecoverableError());
963  unrecoverable_error_message_ = message;
964  unrecoverable_error_location_ = from_here;
965
966  UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
967                            unrecoverable_error_reason_,
968                            ERROR_REASON_LIMIT);
969  NotifyObservers();
970  std::string location;
971  from_here.Write(true, true, &location);
972  LOG(ERROR)
973      << "Unrecoverable error detected at " << location
974      << " -- ProfileSyncService unusable: " << message;
975
976  // Shut all data types down.
977  base::MessageLoop::current()->PostTask(FROM_HERE,
978      base::Bind(&ProfileSyncService::ShutdownImpl,
979                 weak_factory_.GetWeakPtr(),
980                 delete_sync_database ?
981                     syncer::DISABLE_SYNC : syncer::STOP_SYNC));
982}
983
984void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
985  DCHECK(backend_initialized_);
986  directory_data_type_manager_->ReenableType(type);
987}
988
989void ProfileSyncService::UpdateBackendInitUMA(bool success) {
990  if (backend_mode_ != SYNC)
991    return;
992
993  is_first_time_sync_configure_ = !HasSyncSetupCompleted();
994
995  if (is_first_time_sync_configure_) {
996    UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
997  } else {
998    UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
999  }
1000
1001  base::Time on_backend_initialized_time = base::Time::Now();
1002  base::TimeDelta delta = on_backend_initialized_time -
1003      startup_controller_.start_backend_time();
1004  if (is_first_time_sync_configure_) {
1005    UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1006  } else {
1007    UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1008  }
1009}
1010
1011void ProfileSyncService::PostBackendInitialization() {
1012  // Never get here for backup / restore.
1013  DCHECK_EQ(backend_mode_, SYNC);
1014
1015  if (last_backup_time_) {
1016    DCHECK(device_info_sync_service_);
1017    device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1018  }
1019
1020  if (protocol_event_observers_.might_have_observers()) {
1021    backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1022  }
1023
1024  non_blocking_data_type_manager_.ConnectSyncBackend(
1025      backend_->GetSyncContextProxy());
1026
1027  if (type_debug_info_observers_.might_have_observers()) {
1028    backend_->EnableDirectoryTypeDebugInfoForwarding();
1029  }
1030
1031  // If we have a cached passphrase use it to decrypt/encrypt data now that the
1032  // backend is initialized. We want to call this before notifying observers in
1033  // case this operation affects the "passphrase required" status.
1034  ConsumeCachedPassphraseIfPossible();
1035
1036  // The very first time the backend initializes is effectively the first time
1037  // we can say we successfully "synced".  last_synced_time_ will only be null
1038  // in this case, because the pref wasn't restored on StartUp.
1039  if (last_synced_time_.is_null()) {
1040    UpdateLastSyncedTime();
1041  }
1042
1043  if (startup_controller_.auto_start_enabled() && !FirstSetupInProgress()) {
1044    // Backend is initialized but we're not in sync setup, so this must be an
1045    // autostart - mark our sync setup as completed and we'll start syncing
1046    // below.
1047    SetSyncSetupCompleted();
1048  }
1049
1050  // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1051  // data type configuration because observer may flag setup as complete and
1052  // trigger data type configuration.
1053  if (HasSyncSetupCompleted()) {
1054    ConfigureDataTypeManager();
1055  } else {
1056    DCHECK(FirstSetupInProgress());
1057  }
1058
1059  NotifyObservers();
1060}
1061
1062void ProfileSyncService::OnBackendInitialized(
1063    const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1064    const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1065        debug_info_listener,
1066    const std::string& cache_guid,
1067    bool success) {
1068  UpdateBackendInitUMA(success);
1069
1070  if (!success) {
1071    // Something went unexpectedly wrong.  Play it safe: stop syncing at once
1072    // and surface error UI to alert the user sync has stopped.
1073    // Keep the directory around for now so that on restart we will retry
1074    // again and potentially succeed in presence of transient file IO failures
1075    // or permissions issues, etc.
1076    //
1077    // TODO(rlarocque): Consider making this UnrecoverableError less special.
1078    // Unlike every other UnrecoverableError, it does not delete our sync data.
1079    // This exception made sense at the time it was implemented, but our new
1080    // directory corruption recovery mechanism makes it obsolete.  By the time
1081    // we get here, we will have already tried and failed to delete the
1082    // directory.  It would be no big deal if we tried to delete it again.
1083    OnInternalUnrecoverableError(FROM_HERE,
1084                                 "BackendInitialize failure",
1085                                 false,
1086                                 ERROR_REASON_BACKEND_INIT_FAILURE);
1087    return;
1088  }
1089
1090  backend_initialized_ = true;
1091
1092  sync_js_controller_.AttachJsBackend(js_backend);
1093  debug_info_listener_ = debug_info_listener;
1094
1095  SigninClient* signin_client =
1096      ChromeSigninClientFactory::GetForProfile(profile_);
1097  DCHECK(signin_client);
1098  std::string signin_scoped_device_id =
1099      signin_client->GetSigninScopedDeviceId();
1100
1101  // Initialize local device info.
1102  local_device_->Initialize(cache_guid, signin_scoped_device_id);
1103
1104  DVLOG(1) << "Setting preferred types for non-blocking DTM";
1105  non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1106
1107  // Give the DataTypeControllers a handle to the now initialized backend
1108  // as a UserShare.
1109  for (DataTypeController::TypeMap::iterator it =
1110       directory_data_type_controllers_.begin();
1111       it != directory_data_type_controllers_.end(); ++it) {
1112    it->second->OnUserShareReady(GetUserShare());
1113  }
1114
1115  if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1116    ConfigureDataTypeManager();
1117  else
1118    PostBackendInitialization();
1119}
1120
1121void ProfileSyncService::OnSyncCycleCompleted() {
1122  UpdateLastSyncedTime();
1123  if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1124    // Trigger garbage collection of old sessions now that we've downloaded
1125    // any new session data.
1126    base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
1127        &SessionsSyncManager::DoGarbageCollection,
1128            base::AsWeakPtr(sessions_sync_manager_.get())));
1129  }
1130  DVLOG(2) << "Notifying observers sync cycle completed";
1131  NotifySyncCycleCompleted();
1132}
1133
1134void ProfileSyncService::OnExperimentsChanged(
1135    const syncer::Experiments& experiments) {
1136  if (current_experiments_.Matches(experiments))
1137    return;
1138
1139  current_experiments_ = experiments;
1140
1141  // Handle preference-backed experiments first.
1142  if (experiments.gcm_channel_state == syncer::Experiments::SUPPRESSED) {
1143    profile()->GetPrefs()->SetBoolean(prefs::kGCMChannelEnabled, false);
1144    gcm::GCMProfileServiceFactory::GetForProfile(profile())->driver()
1145        ->Disable();
1146  } else {
1147    profile()->GetPrefs()->ClearPref(prefs::kGCMChannelEnabled);
1148    gcm::GCMProfileServiceFactory::GetForProfile(profile())->driver()
1149        ->Enable();
1150  }
1151
1152  profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1153                                    experiments.gcm_invalidations_enabled);
1154
1155  if (experiments.enhanced_bookmarks_enabled) {
1156    profile_->GetPrefs()->SetString(
1157        sync_driver::prefs::kEnhancedBookmarksExtensionId,
1158        experiments.enhanced_bookmarks_ext_id);
1159  } else {
1160    profile_->GetPrefs()->ClearPref(
1161        sync_driver::prefs::kEnhancedBookmarksExtensionId);
1162  }
1163  UpdateBookmarksExperimentState(
1164      profile_->GetPrefs(), g_browser_process->local_state(), true,
1165      experiments.enhanced_bookmarks_enabled ? BOOKMARKS_EXPERIMENT_ENABLED :
1166                                               BOOKMARKS_EXPERIMENT_NONE);
1167
1168  // If this is a first time sync for a client, this will be called before
1169  // OnBackendInitialized() to ensure the new datatypes are available at sync
1170  // setup. As a result, the migrator won't exist yet. This is fine because for
1171  // first time sync cases we're only concerned with making the datatype
1172  // available.
1173  if (migrator_.get() &&
1174      migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1175    DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1176    return;
1177  }
1178
1179  const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1180  syncer::ModelTypeSet to_add;
1181  const syncer::ModelTypeSet to_register =
1182      Difference(to_add, registered_types);
1183  DVLOG(2) << "OnExperimentsChanged called with types: "
1184           << syncer::ModelTypeSetToString(to_add);
1185  DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register);
1186
1187  for (syncer::ModelTypeSet::Iterator it = to_register.First();
1188       it.Good(); it.Inc()) {
1189    // Received notice to enable experimental type. Check if the type is
1190    // registered, and if not register a new datatype controller.
1191    RegisterNewDataType(it.Get());
1192  }
1193
1194  // Check if the user has "Keep Everything Synced" enabled. If so, we want
1195  // to turn on all experimental types if they're not already on. Otherwise we
1196  // leave them off.
1197  // Note: if any types are already registered, we don't turn them on. This
1198  // covers the case where we're already in the process of reconfiguring
1199  // to turn an experimental type on.
1200  if (sync_prefs_.HasKeepEverythingSynced()) {
1201    // Mark all data types as preferred.
1202    sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
1203
1204    // Only automatically turn on types if we have already finished set up.
1205    // Otherwise, just leave the experimental types on by default.
1206    if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_) {
1207      DVLOG(1) << "Dynamically enabling new datatypes: "
1208               << syncer::ModelTypeSetToString(to_register);
1209      OnMigrationNeededForTypes(to_register);
1210    }
1211  }
1212}
1213
1214void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1215  is_auth_in_progress_ = false;
1216  last_auth_error_ = error;
1217
1218  NotifyObservers();
1219}
1220
1221namespace {
1222
1223AuthError ConnectionStatusToAuthError(
1224    syncer::ConnectionStatus status) {
1225  switch (status) {
1226    case syncer::CONNECTION_OK:
1227      return AuthError::AuthErrorNone();
1228      break;
1229    case syncer::CONNECTION_AUTH_ERROR:
1230      return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1231      break;
1232    case syncer::CONNECTION_SERVER_ERROR:
1233      return AuthError(AuthError::CONNECTION_FAILED);
1234      break;
1235    default:
1236      NOTREACHED();
1237      return AuthError(AuthError::CONNECTION_FAILED);
1238  }
1239}
1240
1241}  // namespace
1242
1243void ProfileSyncService::OnConnectionStatusChange(
1244    syncer::ConnectionStatus status) {
1245  connection_status_update_time_ = base::Time::Now();
1246  connection_status_ = status;
1247  if (status == syncer::CONNECTION_AUTH_ERROR) {
1248    // Sync server returned error indicating that access token is invalid. It
1249    // could be either expired or access is revoked. Let's request another
1250    // access token and if access is revoked then request for token will fail
1251    // with corresponding error. If access token is repeatedly reported
1252    // invalid, there may be some issues with server, e.g. authentication
1253    // state is inconsistent on sync and token server. In that case, we
1254    // backoff token requests exponentially to avoid hammering token server
1255    // too much and to avoid getting same token due to token server's caching
1256    // policy. |request_access_token_retry_timer_| is used to backoff request
1257    // triggered by both auth error and failure talking to GAIA server.
1258    // Therefore, we're likely to reach the backoff ceiling more quickly than
1259    // you would expect from looking at the BackoffPolicy if both types of
1260    // errors happen. We shouldn't receive two errors back-to-back without
1261    // attempting a token/sync request in between, thus crank up request delay
1262    // unnecessary. This is because we won't make a sync request if we hit an
1263    // error until GAIA succeeds at sending a new token, and we won't request
1264    // a new token unless sync reports a token failure. But to be safe, don't
1265    // schedule request if this happens.
1266    if (request_access_token_retry_timer_.IsRunning()) {
1267      NOTREACHED();
1268    } else if (request_access_token_backoff_.failure_count() == 0) {
1269      // First time request without delay. Currently invalid token is used
1270      // to initialize sync backend and we'll always end up here. We don't
1271      // want to delay initialization.
1272      request_access_token_backoff_.InformOfRequest(false);
1273      RequestAccessToken();
1274    } else  {
1275      request_access_token_backoff_.InformOfRequest(false);
1276      request_access_token_retry_timer_.Start(
1277          FROM_HERE,
1278          request_access_token_backoff_.GetTimeUntilRelease(),
1279          base::Bind(&ProfileSyncService::RequestAccessToken,
1280                     weak_factory_.GetWeakPtr()));
1281    }
1282  } else {
1283    // Reset backoff time after successful connection.
1284    if (status == syncer::CONNECTION_OK) {
1285      // Request shouldn't be scheduled at this time. But if it is, it's
1286      // possible that sync flips between OK and auth error states rapidly,
1287      // thus hammers token server. To be safe, only reset backoff delay when
1288      // no scheduled request.
1289      if (request_access_token_retry_timer_.IsRunning()) {
1290        NOTREACHED();
1291      } else {
1292        request_access_token_backoff_.Reset();
1293      }
1294    }
1295
1296    const GoogleServiceAuthError auth_error =
1297        ConnectionStatusToAuthError(status);
1298    DVLOG(1) << "Connection status change: " << auth_error.ToString();
1299    UpdateAuthErrorState(auth_error);
1300  }
1301}
1302
1303void ProfileSyncService::StopSyncingPermanently() {
1304  sync_prefs_.SetStartSuppressed(true);
1305  DisableForUser();
1306}
1307
1308void ProfileSyncService::OnPassphraseRequired(
1309    syncer::PassphraseRequiredReason reason,
1310    const sync_pb::EncryptedData& pending_keys) {
1311  DCHECK(backend_.get());
1312  DCHECK(backend_->IsNigoriEnabled());
1313
1314  // TODO(lipalani) : add this check to other locations as well.
1315  if (HasUnrecoverableError()) {
1316    // When unrecoverable error is detected we post a task to shutdown the
1317    // backend. The task might not have executed yet.
1318    return;
1319  }
1320
1321  DVLOG(1) << "Passphrase required with reason: "
1322           << syncer::PassphraseRequiredReasonToString(reason);
1323  passphrase_required_reason_ = reason;
1324
1325  const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1326  if (directory_data_type_manager_) {
1327    // Reconfigure without the encrypted types (excluded implicitly via the
1328    // failed datatypes handler).
1329    directory_data_type_manager_->Configure(types,
1330                                            syncer::CONFIGURE_REASON_CRYPTO);
1331  }
1332
1333  // TODO(rlarocque): Support non-blocking types.  http://crbug.com/351005.
1334
1335  // Notify observers that the passphrase status may have changed.
1336  NotifyObservers();
1337}
1338
1339void ProfileSyncService::OnPassphraseAccepted() {
1340  DVLOG(1) << "Received OnPassphraseAccepted.";
1341
1342  // If the pending keys were resolved via keystore, it's possible we never
1343  // consumed our cached passphrase. Clear it now.
1344  if (!cached_passphrase_.empty())
1345    cached_passphrase_.clear();
1346
1347  // Reset passphrase_required_reason_ since we know we no longer require the
1348  // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1349  // because that can be called by OnPassphraseRequired() if no encrypted data
1350  // types are enabled, and we don't want to clobber the true passphrase error.
1351  passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1352
1353  // Make sure the data types that depend on the passphrase are started at
1354  // this time.
1355  const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1356  if (directory_data_type_manager_) {
1357    // Re-enable any encrypted types if necessary.
1358    directory_data_type_manager_->Configure(types,
1359                                            syncer::CONFIGURE_REASON_CRYPTO);
1360  }
1361
1362  // TODO(rlarocque): Support non-blocking types.  http://crbug.com/351005.
1363
1364  NotifyObservers();
1365}
1366
1367void ProfileSyncService::OnEncryptedTypesChanged(
1368    syncer::ModelTypeSet encrypted_types,
1369    bool encrypt_everything) {
1370  encrypted_types_ = encrypted_types;
1371  encrypt_everything_ = encrypt_everything;
1372  DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1373  DVLOG(1) << "Encrypted types changed to "
1374           << syncer::ModelTypeSetToString(encrypted_types_)
1375           << " (encrypt everything is set to "
1376           << (encrypt_everything_ ? "true" : "false") << ")";
1377  DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1378
1379  NotifyObservers();
1380}
1381
1382void ProfileSyncService::OnEncryptionComplete() {
1383  DVLOG(1) << "Encryption complete";
1384  if (encryption_pending_ && encrypt_everything_) {
1385    encryption_pending_ = false;
1386    // This is to nudge the integration tests when encryption is
1387    // finished.
1388    NotifyObservers();
1389  }
1390}
1391
1392void ProfileSyncService::OnMigrationNeededForTypes(
1393    syncer::ModelTypeSet types) {
1394  DCHECK(backend_initialized_);
1395  DCHECK(directory_data_type_manager_.get());
1396
1397  // Migrator must be valid, because we don't sync until it is created and this
1398  // callback originates from a sync cycle.
1399  migrator_->MigrateTypes(types);
1400}
1401
1402void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1403  last_actionable_error_ = error;
1404  DCHECK_NE(last_actionable_error_.action,
1405            syncer::UNKNOWN_ACTION);
1406  switch (error.action) {
1407    case syncer::UPGRADE_CLIENT:
1408    case syncer::CLEAR_USER_DATA_AND_RESYNC:
1409    case syncer::ENABLE_SYNC_ON_ACCOUNT:
1410    case syncer::STOP_AND_RESTART_SYNC:
1411      // TODO(lipalani) : if setup in progress we want to display these
1412      // actions in the popup. The current experience might not be optimal for
1413      // the user. We just dismiss the dialog.
1414      if (startup_controller_.setup_in_progress()) {
1415        StopSyncingPermanently();
1416        expect_sync_configuration_aborted_ = true;
1417      }
1418      // Trigger an unrecoverable error to stop syncing.
1419      OnInternalUnrecoverableError(FROM_HERE,
1420                                   last_actionable_error_.error_description,
1421                                   true,
1422                                   ERROR_REASON_ACTIONABLE_ERROR);
1423      break;
1424    case syncer::DISABLE_SYNC_AND_ROLLBACK:
1425      backup_rollback_controller_.OnRollbackReceived();
1426      // Fall through to shutdown backend and sign user out.
1427    case syncer::DISABLE_SYNC_ON_CLIENT:
1428      StopSyncingPermanently();
1429#if !defined(OS_CHROMEOS)
1430      // On desktop Chrome, sign out the user after a dashboard clear.
1431      // Skip sign out on ChromeOS/Android.
1432      if (!startup_controller_.auto_start_enabled()) {
1433        SigninManagerFactory::GetForProfile(profile_)->SignOut(
1434            signin_metrics::SERVER_FORCED_DISABLE);
1435      }
1436#endif
1437      break;
1438    case syncer::ROLLBACK_DONE:
1439      backup_rollback_controller_.OnRollbackDone();
1440      break;
1441    case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1442      // Sync disabled by domain admin. we should stop syncing until next
1443      // restart.
1444      sync_disabled_by_admin_ = true;
1445      ShutdownImpl(syncer::DISABLE_SYNC);
1446      break;
1447    default:
1448      NOTREACHED();
1449  }
1450  NotifyObservers();
1451
1452  if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1453      (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1454          !backup_rollback_controller_.StartRollback())) {
1455    // Clean up backup data for sign-out only or when rollback is disabled.
1456    CleanUpBackup();
1457  } else if (error.action == syncer::ROLLBACK_DONE) {
1458    // Shut down ROLLBACK backend and delete backup DB.
1459    ShutdownImpl(syncer::DISABLE_SYNC);
1460    sync_prefs_.ClearFirstSyncTime();
1461  }
1462}
1463
1464void ProfileSyncService::OnConfigureDone(
1465    const DataTypeManager::ConfigureResult& result) {
1466  configure_status_ = result.status;
1467  data_type_status_table_ = result.data_type_status_table;
1468
1469  if (backend_mode_ != SYNC) {
1470    if (configure_status_ == DataTypeManager::OK) {
1471      StartSyncingWithServer();
1472
1473      // Backup is done after models are associated.
1474      if (backend_mode_ == BACKUP)
1475        backup_finished_ = true;
1476
1477      // Asynchronously check whether sync needs to start.
1478      base::MessageLoop::current()->PostTask(
1479          FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1480                                startup_controller_weak_factory_.GetWeakPtr()));
1481    } else if (!expect_sync_configuration_aborted_) {
1482      DVLOG(1) << "Backup/rollback backend failed to configure.";
1483      ShutdownImpl(syncer::STOP_SYNC);
1484    }
1485
1486    return;
1487  }
1488
1489  // We should have cleared our cached passphrase before we get here (in
1490  // OnBackendInitialized()).
1491  DCHECK(cached_passphrase_.empty());
1492
1493  if (!sync_configure_start_time_.is_null()) {
1494    if (result.status == DataTypeManager::OK) {
1495      base::Time sync_configure_stop_time = base::Time::Now();
1496      base::TimeDelta delta = sync_configure_stop_time -
1497          sync_configure_start_time_;
1498      if (is_first_time_sync_configure_) {
1499        UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1500      } else {
1501        UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1502                                  delta);
1503      }
1504    }
1505    sync_configure_start_time_ = base::Time();
1506  }
1507
1508  // Notify listeners that configuration is done.
1509  content::NotificationService::current()->Notify(
1510      chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1511      content::Source<ProfileSyncService>(this),
1512      content::NotificationService::NoDetails());
1513
1514  DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1515  // The possible status values:
1516  //    ABORT - Configuration was aborted. This is not an error, if
1517  //            initiated by user.
1518  //    OK - Some or all types succeeded.
1519  //    Everything else is an UnrecoverableError. So treat it as such.
1520
1521  // First handle the abort case.
1522  if (configure_status_ == DataTypeManager::ABORTED &&
1523      expect_sync_configuration_aborted_) {
1524    DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1525    expect_sync_configuration_aborted_ = false;
1526    return;
1527  }
1528
1529  // Handle unrecoverable error.
1530  if (configure_status_ != DataTypeManager::OK) {
1531    // Something catastrophic had happened. We should only have one
1532    // error representing it.
1533    syncer::SyncError error =
1534        data_type_status_table_.GetUnrecoverableError();
1535    DCHECK(error.IsSet());
1536    std::string message =
1537        "Sync configuration failed with status " +
1538        DataTypeManager::ConfigureStatusToString(configure_status_) +
1539        " caused by " +
1540        syncer::ModelTypeSetToString(
1541            data_type_status_table_.GetUnrecoverableErrorTypes()) +
1542        ": " + error.message();
1543    LOG(ERROR) << "ProfileSyncService error: " << message;
1544    OnInternalUnrecoverableError(error.location(),
1545                                 message,
1546                                 true,
1547                                 ERROR_REASON_CONFIGURATION_FAILURE);
1548    return;
1549  }
1550
1551  // We should never get in a state where we have no encrypted datatypes
1552  // enabled, and yet we still think we require a passphrase for decryption.
1553  DCHECK(!(IsPassphraseRequiredForDecryption() &&
1554           !IsEncryptedDatatypeEnabled()));
1555
1556  // This must be done before we start syncing with the server to avoid
1557  // sending unencrypted data up on a first time sync.
1558  if (encryption_pending_)
1559    backend_->EnableEncryptEverything();
1560  NotifyObservers();
1561
1562  if (migrator_.get() &&
1563      migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1564    // Migration in progress.  Let the migrator know we just finished
1565    // configuring something.  It will be up to the migrator to call
1566    // StartSyncingWithServer() if migration is now finished.
1567    migrator_->OnConfigureDone(result);
1568  } else {
1569    StartSyncingWithServer();
1570  }
1571}
1572
1573void ProfileSyncService::OnConfigureRetry() {
1574  // We should have cleared our cached passphrase before we get here (in
1575  // OnBackendInitialized()).
1576  DCHECK(cached_passphrase_.empty());
1577
1578  OnSyncConfigureRetry();
1579}
1580
1581void ProfileSyncService::OnConfigureStart() {
1582  sync_configure_start_time_ = base::Time::Now();
1583  NotifyObservers();
1584}
1585
1586ProfileSyncService::SyncStatusSummary
1587      ProfileSyncService::QuerySyncStatusSummary() {
1588  if (HasUnrecoverableError()) {
1589    return UNRECOVERABLE_ERROR;
1590  } else if (!backend_) {
1591    return NOT_ENABLED;
1592  } else if (backend_mode_ == BACKUP) {
1593    return BACKUP_USER_DATA;
1594  } else if (backend_mode_ == ROLLBACK) {
1595    return ROLLBACK_USER_DATA;
1596  } else if (backend_.get() && !HasSyncSetupCompleted()) {
1597    return SETUP_INCOMPLETE;
1598  } else if (
1599      backend_.get() && HasSyncSetupCompleted() &&
1600      directory_data_type_manager_.get() &&
1601      directory_data_type_manager_->state() != DataTypeManager::CONFIGURED) {
1602    return DATATYPES_NOT_INITIALIZED;
1603  } else if (ShouldPushChanges()) {
1604    return INITIALIZED;
1605  }
1606  return UNKNOWN_ERROR;
1607}
1608
1609std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1610  SyncStatusSummary status = QuerySyncStatusSummary();
1611
1612  std::string config_status_str =
1613      configure_status_ != DataTypeManager::UNKNOWN ?
1614          DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1615
1616  switch (status) {
1617    case UNRECOVERABLE_ERROR:
1618      return "Unrecoverable error detected";
1619    case NOT_ENABLED:
1620      return "Syncing not enabled";
1621    case SETUP_INCOMPLETE:
1622      return "First time sync setup incomplete";
1623    case DATATYPES_NOT_INITIALIZED:
1624      return "Datatypes not fully initialized";
1625    case INITIALIZED:
1626      return "Sync service initialized";
1627    case BACKUP_USER_DATA:
1628      return "Backing-up user data. Status: " + config_status_str;
1629    case ROLLBACK_USER_DATA:
1630      return "Restoring user data. Status: " + config_status_str;
1631    default:
1632      return "Status unknown: Internal error?";
1633  }
1634}
1635
1636std::string ProfileSyncService::GetBackendInitializationStateString() const {
1637  return startup_controller_.GetBackendInitializationStateString();
1638}
1639
1640bool ProfileSyncService::auto_start_enabled() const {
1641  return startup_controller_.auto_start_enabled();
1642}
1643
1644bool ProfileSyncService::setup_in_progress() const {
1645  return startup_controller_.setup_in_progress();
1646}
1647
1648bool ProfileSyncService::QueryDetailedSyncStatus(
1649    SyncBackendHost::Status* result) {
1650  if (backend_.get() && backend_initialized_) {
1651    *result = backend_->GetDetailedStatus();
1652    return true;
1653  } else {
1654    SyncBackendHost::Status status;
1655    status.sync_protocol_error = last_actionable_error_;
1656    *result = status;
1657    return false;
1658  }
1659}
1660
1661const AuthError& ProfileSyncService::GetAuthError() const {
1662  return last_auth_error_;
1663}
1664
1665bool ProfileSyncService::FirstSetupInProgress() const {
1666  return !HasSyncSetupCompleted() && startup_controller_.setup_in_progress();
1667}
1668
1669void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1670  // This method is a no-op if |setup_in_progress_| remains unchanged.
1671  if (startup_controller_.setup_in_progress() == setup_in_progress)
1672    return;
1673
1674  startup_controller_.set_setup_in_progress(setup_in_progress);
1675  if (!setup_in_progress && sync_initialized())
1676    ReconfigureDatatypeManager();
1677  NotifyObservers();
1678}
1679
1680bool ProfileSyncService::sync_initialized() const {
1681  return backend_initialized_;
1682}
1683
1684bool ProfileSyncService::waiting_for_auth() const {
1685  return is_auth_in_progress_;
1686}
1687
1688const syncer::Experiments& ProfileSyncService::current_experiments() const {
1689  return current_experiments_;
1690}
1691
1692bool ProfileSyncService::HasUnrecoverableError() const {
1693  return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1694}
1695
1696bool ProfileSyncService::IsPassphraseRequired() const {
1697  return passphrase_required_reason_ !=
1698      syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1699}
1700
1701bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1702  // If there is an encrypted datatype enabled and we don't have the proper
1703  // passphrase, we must prompt the user for a passphrase. The only way for the
1704  // user to avoid entering their passphrase is to disable the encrypted types.
1705  return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1706}
1707
1708base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1709  if (last_synced_time_.is_null())
1710    return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1711
1712  base::TimeDelta last_synced = base::Time::Now() - last_synced_time_;
1713
1714  if (last_synced < base::TimeDelta::FromMinutes(1))
1715    return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1716
1717  return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1718                                ui::TimeFormat::LENGTH_SHORT, last_synced);
1719}
1720
1721void ProfileSyncService::UpdateSelectedTypesHistogram(
1722    bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1723  if (!HasSyncSetupCompleted() ||
1724      sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1725    UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1726  }
1727
1728  // Only log the data types that are shown in the sync settings ui.
1729  // Note: the order of these types must match the ordering of
1730  // the respective types in ModelType
1731  const sync_driver::user_selectable_type::UserSelectableSyncType
1732      user_selectable_types[] = {
1733    sync_driver::user_selectable_type::BOOKMARKS,
1734    sync_driver::user_selectable_type::PREFERENCES,
1735    sync_driver::user_selectable_type::PASSWORDS,
1736    sync_driver::user_selectable_type::AUTOFILL,
1737    sync_driver::user_selectable_type::THEMES,
1738    sync_driver::user_selectable_type::TYPED_URLS,
1739    sync_driver::user_selectable_type::EXTENSIONS,
1740    sync_driver::user_selectable_type::APPS,
1741    sync_driver::user_selectable_type::PROXY_TABS
1742  };
1743
1744  COMPILE_ASSERT(32 == syncer::MODEL_TYPE_COUNT, UpdateCustomConfigHistogram);
1745
1746  if (!sync_everything) {
1747    const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1748
1749    syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1750    syncer::ModelTypeSet::Iterator it = type_set.First();
1751
1752    DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1753
1754    for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1755         ++i, it.Inc()) {
1756      const syncer::ModelType type = it.Get();
1757      if (chosen_types.Has(type) &&
1758          (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1759        // Selected type has changed - log it.
1760        UMA_HISTOGRAM_ENUMERATION(
1761            "Sync.CustomSync",
1762            user_selectable_types[i],
1763            sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1764      }
1765    }
1766  }
1767}
1768
1769#if defined(OS_CHROMEOS)
1770void ProfileSyncService::RefreshSpareBootstrapToken(
1771    const std::string& passphrase) {
1772  sync_driver::SystemEncryptor encryptor;
1773  syncer::Cryptographer temp_cryptographer(&encryptor);
1774  // The first 2 params (hostname and username) doesn't have any effect here.
1775  syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1776
1777  std::string bootstrap_token;
1778  if (!temp_cryptographer.AddKey(key_params)) {
1779    NOTREACHED() << "Failed to add key to cryptographer.";
1780  }
1781  temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1782  sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1783}
1784#endif
1785
1786void ProfileSyncService::OnUserChoseDatatypes(
1787    bool sync_everything,
1788    syncer::ModelTypeSet chosen_types) {
1789  if (!backend_.get() && !HasUnrecoverableError()) {
1790    NOTREACHED();
1791    return;
1792  }
1793
1794  UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1795  sync_prefs_.SetKeepEverythingSynced(sync_everything);
1796
1797  if (directory_data_type_manager_.get())
1798    directory_data_type_manager_->ResetDataTypeErrors();
1799  ChangePreferredDataTypes(chosen_types);
1800  AcknowledgeSyncedTypes();
1801  NotifyObservers();
1802}
1803
1804void ProfileSyncService::ChangePreferredDataTypes(
1805    syncer::ModelTypeSet preferred_types) {
1806
1807  DVLOG(1) << "ChangePreferredDataTypes invoked";
1808  const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1809  const syncer::ModelTypeSet registered_preferred_types =
1810      Intersection(registered_types, preferred_types);
1811  sync_prefs_.SetPreferredDataTypes(registered_types,
1812                                    registered_preferred_types);
1813
1814  // Now reconfigure the DTM.
1815  ReconfigureDatatypeManager();
1816
1817  // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too.  Blocked
1818  // on crbug.com/368834.  Until that bug is fixed, it's difficult to tell
1819  // which types should be enabled and when.
1820}
1821
1822syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1823  const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1824  const syncer::ModelTypeSet failed_types =
1825      data_type_status_table_.GetFailedTypes();
1826  return Difference(preferred_types, failed_types);
1827}
1828
1829syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1830  const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1831  const syncer::ModelTypeSet preferred_types =
1832      sync_prefs_.GetPreferredDataTypes(registered_types);
1833  const syncer::ModelTypeSet enforced_types =
1834      Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1835  return Union(preferred_types, enforced_types);
1836}
1837
1838syncer::ModelTypeSet
1839ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1840  const syncer::ModelTypeSet registered_directory_types =
1841      GetRegisteredDirectoryDataTypes();
1842  const syncer::ModelTypeSet preferred_types =
1843      sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1844  const syncer::ModelTypeSet enforced_types =
1845      Intersection(GetDataTypesFromPreferenceProviders(),
1846                   registered_directory_types);
1847  return Union(preferred_types, enforced_types);
1848}
1849
1850syncer::ModelTypeSet
1851ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1852  return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1853}
1854
1855syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1856  // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1857  // we'll need another way to distinguish user-choosable types from
1858  // programmatically-enabled types.
1859  return GetDataTypesFromPreferenceProviders();
1860}
1861
1862syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1863  return Union(GetRegisteredDirectoryDataTypes(),
1864               GetRegisteredNonBlockingDataTypes());
1865}
1866
1867syncer::ModelTypeSet
1868ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1869  syncer::ModelTypeSet registered_types;
1870  // The directory_data_type_controllers_ are determined by command-line flags;
1871  // that's effectively what controls the values returned here.
1872  for (DataTypeController::TypeMap::const_iterator it =
1873       directory_data_type_controllers_.begin();
1874       it != directory_data_type_controllers_.end(); ++it) {
1875    registered_types.Put(it->first);
1876  }
1877  return registered_types;
1878}
1879
1880syncer::ModelTypeSet
1881ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1882  return non_blocking_data_type_manager_.GetRegisteredTypes();
1883}
1884
1885bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1886  syncer::PassphraseType passphrase_type = GetPassphraseType();
1887  return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1888         passphrase_type == syncer::CUSTOM_PASSPHRASE;
1889}
1890
1891syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1892  return backend_->GetPassphraseType();
1893}
1894
1895base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1896  return backend_->GetExplicitPassphraseTime();
1897}
1898
1899bool ProfileSyncService::IsCryptographerReady(
1900    const syncer::BaseTransaction* trans) const {
1901  return backend_.get() && backend_->IsCryptographerReady(trans);
1902}
1903
1904void ProfileSyncService::ConfigurePriorityDataTypes() {
1905  const syncer::ModelTypeSet priority_types =
1906      Intersection(GetPreferredDirectoryDataTypes(),
1907                   syncer::PriorityUserTypes());
1908  if (!priority_types.Empty()) {
1909    const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1910        syncer::CONFIGURE_REASON_RECONFIGURATION :
1911        syncer::CONFIGURE_REASON_NEW_CLIENT;
1912    directory_data_type_manager_->Configure(priority_types, reason);
1913  }
1914}
1915
1916void ProfileSyncService::ConfigureDataTypeManager() {
1917  // Don't configure datatypes if the setup UI is still on the screen - this
1918  // is to help multi-screen setting UIs (like iOS) where they don't want to
1919  // start syncing data until the user is done configuring encryption options,
1920  // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1921  // SetSetupInProgress(false).
1922  if (backend_mode_ == SYNC && startup_controller_.setup_in_progress())
1923    return;
1924
1925  bool restart = false;
1926  if (!directory_data_type_manager_) {
1927    restart = true;
1928    directory_data_type_manager_.reset(
1929        factory_->CreateDataTypeManager(debug_info_listener_,
1930                                        &directory_data_type_controllers_,
1931                                        this,
1932                                        backend_.get(),
1933                                        this));
1934
1935    // We create the migrator at the same time.
1936    migrator_.reset(
1937        new browser_sync::BackendMigrator(
1938            profile_->GetDebugName(), GetUserShare(),
1939            this, directory_data_type_manager_.get(),
1940            base::Bind(&ProfileSyncService::StartSyncingWithServer,
1941                       base::Unretained(this))));
1942  }
1943
1944  syncer::ModelTypeSet types;
1945  syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1946  if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1947    types = syncer::BackupTypes();
1948    reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1949  } else {
1950    types = GetPreferredDirectoryDataTypes();
1951    if (!HasSyncSetupCompleted()) {
1952      reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1953    } else if (restart) {
1954      // Datatype downloads on restart are generally due to newly supported
1955      // datatypes (although it's also possible we're picking up where a failed
1956      // previous configuration left off).
1957      // TODO(sync): consider detecting configuration recovery and setting
1958      // the reason here appropriately.
1959      reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1960    } else {
1961      // The user initiated a reconfiguration (either to add or remove types).
1962      reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1963    }
1964  }
1965
1966  directory_data_type_manager_->Configure(types, reason);
1967}
1968
1969syncer::UserShare* ProfileSyncService::GetUserShare() const {
1970  if (backend_.get() && backend_initialized_) {
1971    return backend_->GetUserShare();
1972  }
1973  NOTREACHED();
1974  return NULL;
1975}
1976
1977syncer::sessions::SyncSessionSnapshot
1978ProfileSyncService::GetLastSessionSnapshot() const {
1979  if (HasSyncingBackend() && backend_initialized_) {
1980    return backend_->GetLastSessionSnapshot();
1981  }
1982  return syncer::sessions::SyncSessionSnapshot();
1983}
1984
1985bool ProfileSyncService::HasUnsyncedItems() const {
1986  if (HasSyncingBackend() && backend_initialized_) {
1987    return backend_->HasUnsyncedItems();
1988  }
1989  NOTREACHED();
1990  return false;
1991}
1992
1993browser_sync::BackendMigrator*
1994ProfileSyncService::GetBackendMigratorForTest() {
1995  return migrator_.get();
1996}
1997
1998void ProfileSyncService::GetModelSafeRoutingInfo(
1999    syncer::ModelSafeRoutingInfo* out) const {
2000  if (backend_.get() && backend_initialized_) {
2001    backend_->GetModelSafeRoutingInfo(out);
2002  } else {
2003    NOTREACHED();
2004  }
2005}
2006
2007base::Value* ProfileSyncService::GetTypeStatusMap() const {
2008  scoped_ptr<base::ListValue> result(new base::ListValue());
2009
2010  if (!backend_.get() || !backend_initialized_) {
2011    return result.release();
2012  }
2013
2014  DataTypeStatusTable::TypeErrorMap error_map =
2015      data_type_status_table_.GetAllErrors();
2016  ModelTypeSet active_types;
2017  ModelTypeSet passive_types;
2018  ModelSafeRoutingInfo routing_info;
2019  backend_->GetModelSafeRoutingInfo(&routing_info);
2020  for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
2021       it != routing_info.end(); ++it) {
2022    if (it->second == syncer::GROUP_PASSIVE) {
2023      passive_types.Put(it->first);
2024    } else {
2025      active_types.Put(it->first);
2026    }
2027  }
2028
2029  SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
2030  ModelTypeSet &throttled_types(detailed_status.throttled_types);
2031  ModelTypeSet registered = GetRegisteredDataTypes();
2032  scoped_ptr<base::DictionaryValue> type_status_header(
2033      new base::DictionaryValue());
2034
2035  type_status_header->SetString("name", "Model Type");
2036  type_status_header->SetString("status", "header");
2037  type_status_header->SetString("value", "Group Type");
2038  type_status_header->SetString("num_entries", "Total Entries");
2039  type_status_header->SetString("num_live", "Live Entries");
2040  result->Append(type_status_header.release());
2041
2042  scoped_ptr<base::DictionaryValue> type_status;
2043  for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2044    ModelType type = it.Get();
2045
2046    type_status.reset(new base::DictionaryValue());
2047    type_status->SetString("name", ModelTypeToString(type));
2048
2049    if (error_map.find(type) != error_map.end()) {
2050      const syncer::SyncError &error = error_map.find(type)->second;
2051      DCHECK(error.IsSet());
2052      switch (error.GetSeverity()) {
2053        case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2054            std::string error_text = "Error: " + error.location().ToString() +
2055                ", " + error.GetMessagePrefix() + error.message();
2056            type_status->SetString("status", "error");
2057            type_status->SetString("value", error_text);
2058          }
2059          break;
2060        case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2061          type_status->SetString("status", "disabled");
2062          type_status->SetString("value", error.message());
2063          break;
2064        default:
2065          NOTREACHED() << "Unexpected error severity.";
2066          break;
2067      }
2068    } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2069      // Show a proxy type in "ok" state unless it is disabled by user.
2070      DCHECK(!throttled_types.Has(type));
2071      type_status->SetString("status", "ok");
2072      type_status->SetString("value", "Passive");
2073    } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2074      type_status->SetString("status", "warning");
2075      type_status->SetString("value", "Passive, Throttled");
2076    } else if (passive_types.Has(type)) {
2077      type_status->SetString("status", "warning");
2078      type_status->SetString("value", "Passive");
2079    } else if (throttled_types.Has(type)) {
2080      type_status->SetString("status", "warning");
2081      type_status->SetString("value", "Throttled");
2082    } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2083      type_status->SetString("status", "ok");
2084      type_status->SetString("value", "Non-Blocking");
2085    } else if (active_types.Has(type)) {
2086      type_status->SetString("status", "ok");
2087      type_status->SetString("value", "Active: " +
2088                             ModelSafeGroupToString(routing_info[type]));
2089    } else {
2090      type_status->SetString("status", "warning");
2091      type_status->SetString("value", "Disabled by User");
2092    }
2093
2094    int live_count = detailed_status.num_entries_by_type[type] -
2095        detailed_status.num_to_delete_entries_by_type[type];
2096    type_status->SetInteger("num_entries",
2097                            detailed_status.num_entries_by_type[type]);
2098    type_status->SetInteger("num_live", live_count);
2099
2100    result->Append(type_status.release());
2101  }
2102  return result.release();
2103}
2104
2105void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2106  if (!backend_)
2107    return;
2108  backend_->DeactivateDataType(type);
2109}
2110
2111void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2112  // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2113  // If the backend isn't running yet, OnBackendInitialized() will call this
2114  // method again after the backend starts up.
2115  if (cached_passphrase_.empty() || !sync_initialized())
2116    return;
2117
2118  // Backend is up and running, so we can consume the cached passphrase.
2119  std::string passphrase = cached_passphrase_;
2120  cached_passphrase_.clear();
2121
2122  // If we need a passphrase to decrypt data, try the cached passphrase.
2123  if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2124    if (SetDecryptionPassphrase(passphrase)) {
2125      DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2126      return;
2127    }
2128  }
2129
2130  // If we get here, we don't have pending keys (or at least, the passphrase
2131  // doesn't decrypt them) - just try to re-encrypt using the encryption
2132  // passphrase.
2133  if (!IsUsingSecondaryPassphrase())
2134    SetEncryptionPassphrase(passphrase, IMPLICIT);
2135}
2136
2137void ProfileSyncService::RequestAccessToken() {
2138  // Only one active request at a time.
2139  if (access_token_request_ != NULL)
2140    return;
2141  request_access_token_retry_timer_.Stop();
2142  OAuth2TokenService::ScopeSet oauth2_scopes;
2143  oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2144
2145  // Invalidate previous token, otherwise token service will return the same
2146  // token again.
2147  const std::string& account_id = signin_->GetAccountIdToUse();
2148  if (!access_token_.empty()) {
2149    oauth2_token_service_->InvalidateToken(
2150        account_id, oauth2_scopes, access_token_);
2151  }
2152
2153  access_token_.clear();
2154
2155  token_request_time_ = base::Time::Now();
2156  token_receive_time_ = base::Time();
2157  next_token_request_time_ = base::Time();
2158  access_token_request_ =
2159      oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2160}
2161
2162void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2163                                                 PassphraseType type) {
2164  // This should only be called when the backend has been initialized.
2165  DCHECK(sync_initialized());
2166  DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2167      "Data is already encrypted using an explicit passphrase";
2168  DCHECK(!(type == EXPLICIT &&
2169           passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2170         "Can not set explicit passphrase when decryption is needed.";
2171
2172  DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2173           << " passphrase for encryption.";
2174  if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2175    // REASON_ENCRYPTION implies that the cryptographer does not have pending
2176    // keys. Hence, as long as we're not trying to do an invalid passphrase
2177    // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2178    // will succeed. If for some reason a new encryption key arrives via
2179    // sync later, the SBH will trigger another OnPassphraseRequired().
2180    passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2181    NotifyObservers();
2182  }
2183  backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2184}
2185
2186bool ProfileSyncService::SetDecryptionPassphrase(
2187    const std::string& passphrase) {
2188  if (IsPassphraseRequired()) {
2189    DVLOG(1) << "Setting passphrase for decryption.";
2190    return backend_->SetDecryptionPassphrase(passphrase);
2191  } else {
2192    NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2193                    "IsPassphraseRequired() is false.";
2194    return false;
2195  }
2196}
2197
2198bool ProfileSyncService::EncryptEverythingAllowed() const {
2199  return encrypt_everything_allowed_;
2200}
2201
2202void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2203  DCHECK(allowed || !backend_initialized_ || !EncryptEverythingEnabled());
2204  encrypt_everything_allowed_ = allowed;
2205}
2206
2207void ProfileSyncService::EnableEncryptEverything() {
2208  DCHECK(EncryptEverythingAllowed());
2209
2210  // Tests override sync_initialized() to always return true, so we
2211  // must check that instead of |backend_initialized_|.
2212  // TODO(akalin): Fix the above. :/
2213  DCHECK(sync_initialized());
2214  // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2215  // problems around cancelling encryption in the background (crbug.com/119649).
2216  if (!encrypt_everything_)
2217    encryption_pending_ = true;
2218}
2219
2220bool ProfileSyncService::encryption_pending() const {
2221  // We may be called during the setup process before we're
2222  // initialized (via IsEncryptedDatatypeEnabled and
2223  // IsPassphraseRequiredForDecryption).
2224  return encryption_pending_;
2225}
2226
2227bool ProfileSyncService::EncryptEverythingEnabled() const {
2228  DCHECK(backend_initialized_);
2229  return encrypt_everything_ || encryption_pending_;
2230}
2231
2232syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2233  DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2234  // We may be called during the setup process before we're
2235  // initialized.  In this case, we default to the sensitive types.
2236  return encrypted_types_;
2237}
2238
2239void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2240  NotifyObservers();
2241  if (is_sync_managed) {
2242    DisableForUser();
2243  } else {
2244    // Sync is no longer disabled by policy. Try starting it up if appropriate.
2245    startup_controller_.TryStart();
2246  }
2247}
2248
2249void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2250                                               const std::string& username,
2251                                               const std::string& password) {
2252  if (!sync_prefs_.IsStartSuppressed() && !password.empty()) {
2253    cached_passphrase_ = password;
2254    // Try to consume the passphrase we just cached. If the sync backend
2255    // is not running yet, the passphrase will remain cached until the
2256    // backend starts up.
2257    ConsumeCachedPassphraseIfPossible();
2258  }
2259#if defined(OS_CHROMEOS)
2260  RefreshSpareBootstrapToken(password);
2261#endif
2262  if (!sync_initialized() || GetAuthError().state() != AuthError::NONE) {
2263    // Track the fact that we're still waiting for auth to complete.
2264    is_auth_in_progress_ = true;
2265  }
2266}
2267
2268void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2269                                         const std::string& username) {
2270  sync_disabled_by_admin_ = false;
2271  DisableForUser();
2272
2273  if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2274    need_backup_ = true;
2275    backup_finished_ = false;
2276  }
2277}
2278
2279void ProfileSyncService::AddObserver(
2280    ProfileSyncServiceBase::Observer* observer) {
2281  observers_.AddObserver(observer);
2282}
2283
2284void ProfileSyncService::RemoveObserver(
2285    ProfileSyncServiceBase::Observer* observer) {
2286  observers_.RemoveObserver(observer);
2287}
2288
2289void ProfileSyncService::AddProtocolEventObserver(
2290    browser_sync::ProtocolEventObserver* observer) {
2291  protocol_event_observers_.AddObserver(observer);
2292  if (HasSyncingBackend()) {
2293    backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2294  }
2295}
2296
2297void ProfileSyncService::RemoveProtocolEventObserver(
2298    browser_sync::ProtocolEventObserver* observer) {
2299  protocol_event_observers_.RemoveObserver(observer);
2300  if (HasSyncingBackend() &&
2301      !protocol_event_observers_.might_have_observers()) {
2302    backend_->DisableProtocolEventForwarding();
2303  }
2304}
2305
2306void ProfileSyncService::AddTypeDebugInfoObserver(
2307    syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2308  type_debug_info_observers_.AddObserver(type_debug_info_observer);
2309  if (type_debug_info_observers_.might_have_observers() &&
2310      backend_initialized_) {
2311    backend_->EnableDirectoryTypeDebugInfoForwarding();
2312  }
2313}
2314
2315void ProfileSyncService::RemoveTypeDebugInfoObserver(
2316    syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2317  type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2318  if (!type_debug_info_observers_.might_have_observers() &&
2319      backend_initialized_) {
2320    backend_->DisableDirectoryTypeDebugInfoForwarding();
2321  }
2322}
2323
2324void ProfileSyncService::AddPreferenceProvider(
2325    SyncTypePreferenceProvider* provider) {
2326  DCHECK(!HasPreferenceProvider(provider))
2327      << "Providers may only be added once!";
2328  preference_providers_.insert(provider);
2329}
2330
2331void ProfileSyncService::RemovePreferenceProvider(
2332    SyncTypePreferenceProvider* provider) {
2333  DCHECK(HasPreferenceProvider(provider))
2334      << "Only providers that have been added before can be removed!";
2335  preference_providers_.erase(provider);
2336}
2337
2338bool ProfileSyncService::HasPreferenceProvider(
2339    SyncTypePreferenceProvider* provider) const {
2340  return preference_providers_.count(provider) > 0;
2341}
2342
2343namespace {
2344
2345class GetAllNodesRequestHelper
2346    : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2347 public:
2348  GetAllNodesRequestHelper(
2349      syncer::ModelTypeSet requested_types,
2350      const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2351
2352  void OnReceivedNodesForTypes(
2353      const std::vector<syncer::ModelType>& types,
2354      ScopedVector<base::ListValue> scoped_node_lists);
2355
2356 private:
2357  friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2358  virtual ~GetAllNodesRequestHelper();
2359
2360  scoped_ptr<base::ListValue> result_accumulator_;
2361
2362  syncer::ModelTypeSet awaiting_types_;
2363  base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2364};
2365
2366GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2367    syncer::ModelTypeSet requested_types,
2368    const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2369    : result_accumulator_(new base::ListValue()),
2370      awaiting_types_(requested_types),
2371      callback_(callback) {}
2372
2373GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2374  if (!awaiting_types_.Empty()) {
2375    DLOG(WARNING)
2376        << "GetAllNodesRequest deleted before request was fulfilled.  "
2377        << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2378  }
2379}
2380
2381// Called when the set of nodes for a type or set of types has been returned.
2382//
2383// The nodes for several types can be returned at the same time by specifying
2384// their types in the |types| array, and putting their results at the
2385// correspnding indices in the |scoped_node_lists|.
2386void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2387    const std::vector<syncer::ModelType>& types,
2388    ScopedVector<base::ListValue> scoped_node_lists) {
2389  DCHECK_EQ(types.size(), scoped_node_lists.size());
2390
2391  // Take unsafe ownership of the node list.
2392  std::vector<base::ListValue*> node_lists;
2393  scoped_node_lists.release(&node_lists);
2394
2395  for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2396    const ModelType type = types[i];
2397    base::ListValue* node_list = node_lists[i];
2398
2399    // Add these results to our list.
2400    scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2401    type_dict->SetString("type", ModelTypeToString(type));
2402    type_dict->Set("nodes", node_list);
2403    result_accumulator_->Append(type_dict.release());
2404
2405    // Remember that this part of the request is satisfied.
2406    awaiting_types_.Remove(type);
2407  }
2408
2409  if (awaiting_types_.Empty()) {
2410    callback_.Run(result_accumulator_.Pass());
2411    callback_.Reset();
2412  }
2413}
2414
2415}  // namespace
2416
2417void ProfileSyncService::GetAllNodes(
2418    const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2419  ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2420  directory_types.PutAll(syncer::ControlTypes());
2421  scoped_refptr<GetAllNodesRequestHelper> helper =
2422      new GetAllNodesRequestHelper(directory_types, callback);
2423
2424  if (!backend_initialized_) {
2425    // If there's no backend available to fulfill the request, handle it here.
2426    ScopedVector<base::ListValue> empty_results;
2427    std::vector<ModelType> type_vector;
2428    for (ModelTypeSet::Iterator it = directory_types.First();
2429         it.Good(); it.Inc()) {
2430      type_vector.push_back(it.Get());
2431      empty_results.push_back(new base::ListValue());
2432    }
2433    helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2434  } else {
2435    backend_->GetAllNodesForTypes(
2436        directory_types,
2437        base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2438  }
2439}
2440
2441bool ProfileSyncService::HasObserver(
2442    ProfileSyncServiceBase::Observer* observer) const {
2443  return observers_.HasObserver(observer);
2444}
2445
2446base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2447  return sync_js_controller_.AsWeakPtr();
2448}
2449
2450void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2451  UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2452}
2453
2454// static
2455bool ProfileSyncService::IsSyncEnabled() {
2456  // We have switches::kEnableSync just in case we need to change back to
2457  // sync-disabled-by-default on a platform.
2458  return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync);
2459}
2460
2461bool ProfileSyncService::IsManaged() const {
2462  return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2463}
2464
2465bool ProfileSyncService::ShouldPushChanges() {
2466  // True only after all bootstrapping has succeeded: the sync backend
2467  // is initialized, all enabled data types are consistent with one
2468  // another, and no unrecoverable error has transpired.
2469  if (HasUnrecoverableError())
2470    return false;
2471
2472  if (!directory_data_type_manager_)
2473    return false;
2474
2475  return directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
2476}
2477
2478void ProfileSyncService::StopAndSuppress() {
2479  sync_prefs_.SetStartSuppressed(true);
2480  if (HasSyncingBackend()) {
2481    backend_->UnregisterInvalidationIds();
2482  }
2483  ShutdownImpl(syncer::STOP_SYNC);
2484}
2485
2486bool ProfileSyncService::IsStartSuppressed() const {
2487  return sync_prefs_.IsStartSuppressed();
2488}
2489
2490SigninManagerBase* ProfileSyncService::signin() const {
2491  if (!signin_)
2492    return NULL;
2493  return signin_->GetOriginal();
2494}
2495
2496void ProfileSyncService::UnsuppressAndStart() {
2497  DCHECK(profile_);
2498  sync_prefs_.SetStartSuppressed(false);
2499  if (signin_.get() && !signin_->GetOriginal()->IsAuthenticated()) {
2500    signin_->GetOriginal()->SetAuthenticatedUsername(
2501        profile_->GetPrefs()->GetString(prefs::kGoogleServicesUsername));
2502  }
2503  startup_controller_.TryStart();
2504}
2505
2506void ProfileSyncService::AcknowledgeSyncedTypes() {
2507  sync_prefs_.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2508}
2509
2510void ProfileSyncService::ReconfigureDatatypeManager() {
2511  // If we haven't initialized yet, don't configure the DTM as it could cause
2512  // association to start before a Directory has even been created.
2513  if (backend_initialized_) {
2514    DCHECK(backend_.get());
2515    ConfigureDataTypeManager();
2516  } else if (HasUnrecoverableError()) {
2517    // There is nothing more to configure. So inform the listeners,
2518    NotifyObservers();
2519
2520    DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2521             << "Unrecoverable error.";
2522  } else {
2523    DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2524             << "initialized";
2525  }
2526}
2527
2528syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2529    const {
2530  syncer::ModelTypeSet types;
2531  for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2532           preference_providers_.begin();
2533       it != preference_providers_.end();
2534       ++it) {
2535    types.PutAll((*it)->GetPreferredDataTypes());
2536  }
2537  return types;
2538}
2539
2540const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2541    const {
2542  return data_type_status_table_;
2543}
2544
2545void ProfileSyncService::OnInternalUnrecoverableError(
2546    const tracked_objects::Location& from_here,
2547    const std::string& message,
2548    bool delete_sync_database,
2549    UnrecoverableErrorReason reason) {
2550  DCHECK(!HasUnrecoverableError());
2551  unrecoverable_error_reason_ = reason;
2552  OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2553}
2554
2555syncer::SyncManagerFactory::MANAGER_TYPE
2556ProfileSyncService::GetManagerType() const {
2557  switch (backend_mode_) {
2558    case SYNC:
2559      return syncer::SyncManagerFactory::NORMAL;
2560    case BACKUP:
2561      return syncer::SyncManagerFactory::BACKUP;
2562    case ROLLBACK:
2563      return syncer::SyncManagerFactory::ROLLBACK;
2564    case IDLE:
2565      NOTREACHED();
2566  }
2567  return syncer::SyncManagerFactory::NORMAL;
2568}
2569
2570bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2571  return request_access_token_retry_timer_.IsRunning();
2572}
2573
2574std::string ProfileSyncService::GetAccessTokenForTest() const {
2575  return access_token_;
2576}
2577
2578WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2579  return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2580}
2581
2582syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2583  return sessions_sync_manager_.get();
2584}
2585
2586syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2587  return device_info_sync_service_.get();
2588}
2589
2590ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2591    : connection_status(syncer::CONNECTION_NOT_ATTEMPTED),
2592      last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2593ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2594
2595ProfileSyncService::SyncTokenStatus
2596ProfileSyncService::GetSyncTokenStatus() const {
2597  SyncTokenStatus status;
2598  status.connection_status_update_time = connection_status_update_time_;
2599  status.connection_status = connection_status_;
2600  status.token_request_time = token_request_time_;
2601  status.token_receive_time = token_receive_time_;
2602  status.last_get_token_error = last_get_token_error_;
2603  if (request_access_token_retry_timer_.IsRunning())
2604    status.next_token_request_time = next_token_request_time_;
2605  return status;
2606}
2607
2608void ProfileSyncService::OverrideNetworkResourcesForTest(
2609    scoped_ptr<syncer::NetworkResources> network_resources) {
2610  network_resources_ = network_resources.Pass();
2611}
2612
2613bool ProfileSyncService::HasSyncingBackend() const {
2614  return backend_mode_ != SYNC ? false : backend_ != NULL;
2615}
2616
2617void ProfileSyncService::UpdateFirstSyncTimePref() {
2618  if (signin_->GetEffectiveUsername().empty()) {
2619    // Clear if user's not signed in and rollback is done.
2620    if (backend_mode_ != ROLLBACK)
2621      sync_prefs_.ClearFirstSyncTime();
2622  } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2623      backend_mode_ == SYNC) {
2624    // Set if not set before and it's syncing now.
2625    sync_prefs_.SetFirstSyncTime(base::Time::Now());
2626  }
2627}
2628
2629void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2630  base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2631  if (first_sync_time.is_null())
2632    return;
2633
2634  clear_browsing_data_.Run(browsing_data_remover_observer_,
2635                           profile_,
2636                           first_sync_time,
2637                           base::Time::Now());
2638}
2639
2640void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2641    BrowsingDataRemover::Observer* observer) {
2642  browsing_data_remover_observer_ = observer;
2643}
2644
2645void ProfileSyncService::SetClearingBrowseringDataForTesting(
2646    base::Callback<void(BrowsingDataRemover::Observer* observer,
2647                        Profile*,
2648                        base::Time,
2649                        base::Time)> c) {
2650  clear_browsing_data_ = c;
2651}
2652
2653GURL ProfileSyncService::GetSyncServiceURL(
2654    const base::CommandLine& command_line) {
2655  // By default, dev, canary, and unbranded Chromium users will go to the
2656  // development servers. Development servers have more features than standard
2657  // sync servers. Users with officially-branded Chrome stable and beta builds
2658  // will go to the standard sync servers.
2659  GURL result(kDevServerUrl);
2660
2661  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
2662  if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
2663      channel == chrome::VersionInfo::CHANNEL_BETA) {
2664    result = GURL(kSyncServerUrl);
2665  }
2666
2667  // Override the sync server URL from the command-line, if sync server
2668  // command-line argument exists.
2669  if (command_line.HasSwitch(switches::kSyncServiceURL)) {
2670    std::string value(command_line.GetSwitchValueASCII(
2671        switches::kSyncServiceURL));
2672    if (!value.empty()) {
2673      GURL custom_sync_url(value);
2674      if (custom_sync_url.is_valid()) {
2675        result = custom_sync_url;
2676      } else {
2677        LOG(WARNING) << "The following sync URL specified at the command-line "
2678                     << "is invalid: " << value;
2679      }
2680    }
2681  }
2682  return result;
2683}
2684
2685void ProfileSyncService::CheckSyncBackupIfNeeded() {
2686  DCHECK_EQ(backend_mode_, SYNC);
2687
2688#if defined(ENABLE_PRE_SYNC_BACKUP)
2689  // Check backup once a day.
2690  if (!last_backup_time_ &&
2691      (last_synced_time_.is_null() ||
2692          base::Time::Now() - last_synced_time_ >=
2693              base::TimeDelta::FromDays(1))) {
2694    // If sync thread is set, need to serialize check on sync thread after
2695    // closing backup DB.
2696    if (sync_thread_) {
2697      sync_thread_->message_loop_proxy()->PostTask(
2698          FROM_HERE,
2699          base::Bind(syncer::CheckSyncDbLastModifiedTime,
2700                     profile_->GetPath().Append(kSyncBackupDataFolderName),
2701                     base::MessageLoopProxy::current(),
2702                     base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2703                                weak_factory_.GetWeakPtr())));
2704    } else {
2705      content::BrowserThread::PostTask(
2706          content::BrowserThread::FILE, FROM_HERE,
2707          base::Bind(syncer::CheckSyncDbLastModifiedTime,
2708                     profile_->GetPath().Append(kSyncBackupDataFolderName),
2709                     base::MessageLoopProxy::current(),
2710                     base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2711                                weak_factory_.GetWeakPtr())));
2712    }
2713  }
2714#endif
2715}
2716
2717void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2718  last_backup_time_.reset(new base::Time(backup_time));
2719
2720  DCHECK(device_info_sync_service_);
2721  device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2722}
2723
2724void ProfileSyncService::TryStartSyncAfterBackup() {
2725  startup_controller_.Reset(GetRegisteredDataTypes());
2726  startup_controller_.TryStart();
2727}
2728
2729void ProfileSyncService::CleanUpBackup() {
2730  sync_prefs_.ClearFirstSyncTime();
2731  profile_->GetIOTaskRunner()->PostTask(
2732      FROM_HERE,
2733      base::Bind(base::IgnoreResult(base::DeleteFile),
2734                 profile_->GetPath().Append(kSyncBackupDataFolderName),
2735                 true));
2736}
2737
2738bool ProfileSyncService::NeedBackup() const {
2739  return need_backup_;
2740}
2741
2742base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2743  return device_info_sync_service_->GetLocalDeviceBackupTime();
2744}
2745