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