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