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