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