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