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