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