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