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.
5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/location.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/strings/string16.h"
21 #include "base/time/time.h"
22 #include "base/timer/timer.h"
23 #include "chrome/browser/browsing_data/browsing_data_remover.h"
24 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
25 #include "chrome/browser/sync/backup_rollback_controller.h"
26 #include "chrome/browser/sync/glue/local_device_info_provider.h"
27 #include "chrome/browser/sync/glue/sync_backend_host.h"
28 #include "chrome/browser/sync/glue/synced_device_tracker.h"
29 #include "chrome/browser/sync/profile_sync_service_base.h"
30 #include "chrome/browser/sync/profile_sync_service_observer.h"
31 #include "chrome/browser/sync/protocol_event_observer.h"
32 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
33 #include "chrome/browser/sync/startup_controller.h"
34 #include "components/keyed_service/core/keyed_service.h"
35 #include "components/signin/core/browser/signin_manager_base.h"
36 #include "components/sync_driver/data_type_controller.h"
37 #include "components/sync_driver/data_type_encryption_handler.h"
38 #include "components/sync_driver/data_type_manager.h"
39 #include "components/sync_driver/data_type_manager_observer.h"
40 #include "components/sync_driver/data_type_status_table.h"
41 #include "components/sync_driver/non_blocking_data_type_manager.h"
42 #include "components/sync_driver/sync_frontend.h"
43 #include "components/sync_driver/sync_prefs.h"
44 #include "google_apis/gaia/google_service_auth_error.h"
45 #include "google_apis/gaia/oauth2_token_service.h"
46 #include "net/base/backoff_entry.h"
47 #include "sync/internal_api/public/base/model_type.h"
48 #include "sync/internal_api/public/engine/model_safe_worker.h"
49 #include "sync/internal_api/public/shutdown_reason.h"
50 #include "sync/internal_api/public/sync_manager_factory.h"
51 #include "sync/internal_api/public/util/experiments.h"
52 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
53 #include "sync/js/sync_js_controller.h"
57 class ProfileOAuth2TokenService
;
58 class ProfileSyncComponentsFactory
;
59 class SupervisedUserSigninManagerWrapper
;
60 class SyncErrorController
;
61 class SyncTypePreferenceProvider
;
67 namespace browser_sync
{
68 class BackendMigrator
;
72 class OpenTabsUIDelegate
;
75 class SyncSessionSnapshot
;
76 } // namespace sessions
77 } // namespace browser_sync
79 namespace sync_driver
{
80 class ChangeProcessor
;
81 class DataTypeManager
;
82 } // namespace sync_driver
85 class BaseTransaction
;
86 class NetworkResources
;
87 struct CommitCounters
;
88 struct StatusCounters
;
89 struct SyncCredentials
;
90 struct UpdateCounters
;
96 } // namespace sync_pb
98 using browser_sync::LocalDeviceInfoProvider
;
99 using browser_sync::SessionsSyncManager
;
101 // ProfileSyncService is the layer between browser subsystems like bookmarks,
102 // and the sync backend. Each subsystem is logically thought of as being
105 // Individual datatypes can, at any point, be in a variety of stages of being
106 // "enabled". Here are some specific terms for concepts used in this class:
108 // 'Registered' (feature suppression for a datatype)
110 // When a datatype is registered, the user has the option of syncing it.
111 // The sync opt-in UI will show only registered types; a checkbox should
112 // never be shown for an unregistered type, and nor should it ever be
115 // A datatype is considered registered once RegisterDataTypeController
116 // has been called with that datatype's DataTypeController.
118 // 'Preferred' (user preferences and opt-out for a datatype)
120 // This means the user's opt-in or opt-out preference on a per-datatype
121 // basis. The sync service will try to make active exactly these types.
122 // If a user has opted out of syncing a particular datatype, it will
123 // be registered, but not preferred.
125 // This state is controlled by the ConfigurePreferredDataTypes and
126 // GetPreferredDataTypes. They are stored in the preferences system,
127 // and persist; though if a datatype is not registered, it cannot
128 // be a preferred datatype.
130 // 'Active' (run-time initialization of sync system for a datatype)
132 // An active datatype is a preferred datatype that is actively being
133 // synchronized: the syncer has been instructed to querying the server
134 // for this datatype, first-time merges have finished, and there is an
135 // actively installed ChangeProcessor that listens for changes to this
136 // datatype, propagating such changes into and out of the sync backend
139 // When a datatype is in the process of becoming active, it may be
140 // in some intermediate state. Those finer-grained intermediate states
141 // are differentiated by the DataTypeController state.
143 // Sync Configuration:
145 // Sync configuration is accomplished via the following APIs:
146 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
147 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
148 // using the passed passphrase.
149 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
152 // Additionally, the current sync configuration can be fetched by calling
153 // * GetRegisteredDataTypes()
154 // * GetPreferredDataTypes()
155 // * GetActiveDataTypes()
156 // * IsUsingSecondaryPassphrase()
157 // * EncryptEverythingEnabled()
158 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
160 // The "sync everything" state cannot be read from ProfileSyncService, but
161 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
163 // Initial sync setup:
165 // For privacy reasons, it is usually desirable to avoid syncing any data
166 // types until the user has finished setting up sync. There are two APIs
167 // that control the initial sync download:
169 // * SetSyncSetupCompleted()
170 // * SetSetupInProgress()
172 // SetSyncSetupCompleted() should be called once the user has finished setting
173 // up sync at least once on their account. SetSetupInProgress(true) should be
174 // called while the user is actively configuring their account, and then
175 // SetSetupInProgress(false) should be called when configuration is complete.
176 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
177 // been called, then the sync engine knows not to download any user data.
179 // When initial sync is complete, the UI code should call
180 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
181 // tell the sync engine that setup is completed and it can begin downloading
182 // data from the sync server.
184 class ProfileSyncService
: public ProfileSyncServiceBase
,
185 public sync_driver::SyncFrontend
,
186 public sync_driver::SyncPrefObserver
,
187 public sync_driver::DataTypeManagerObserver
,
188 public syncer::UnrecoverableErrorHandler
,
190 public sync_driver::DataTypeEncryptionHandler
,
191 public OAuth2TokenService::Consumer
,
192 public OAuth2TokenService::Observer
,
193 public SigninManagerBase::Observer
{
195 typedef browser_sync::SyncBackendHost::Status Status
;
197 // Status of sync server connection, sync token and token request.
198 struct SyncTokenStatus
{
202 // Sync server connection status reported by sync backend.
203 base::Time connection_status_update_time
;
204 syncer::ConnectionStatus connection_status
;
206 // Times when OAuth2 access token is requested and received.
207 base::Time token_request_time
;
208 base::Time token_receive_time
;
210 // Error returned by OAuth2TokenService for token request and time when
211 // next request is scheduled.
212 GoogleServiceAuthError last_get_token_error
;
213 base::Time next_token_request_time
;
216 enum SyncEventCodes
{
217 MIN_SYNC_EVENT_CODE
= 0,
219 // Events starting the sync service.
220 START_FROM_NTP
= 1, // Sync was started from the ad in NTP
221 START_FROM_WRENCH
= 2, // Sync was started from the Wrench menu.
222 START_FROM_OPTIONS
= 3, // Sync was started from Wrench->Options.
223 START_FROM_BOOKMARK_MANAGER
= 4, // Sync was started from Bookmark manager.
224 START_FROM_PROFILE_MENU
= 5, // Sync was started from multiprofile menu.
225 START_FROM_URL
= 6, // Sync was started from a typed URL.
227 // Events regarding cancellation of the signon process of sync.
228 CANCEL_FROM_SIGNON_WITHOUT_AUTH
= 10, // Cancelled before submitting
229 // username and password.
230 CANCEL_DURING_SIGNON
= 11, // Cancelled after auth.
231 CANCEL_DURING_CONFIGURE
= 12, // Cancelled before choosing data
232 // types and clicking OK.
233 // Events resulting in the stoppage of sync service.
234 STOP_FROM_OPTIONS
= 20, // Sync was stopped from Wrench->Options.
235 STOP_FROM_ADVANCED_DIALOG
= 21, // Sync was stopped via advanced settings.
237 // Miscellaneous events caused by sync service.
242 // Used to specify the kind of passphrase with which sync data is encrypted.
243 enum PassphraseType
{
244 IMPLICIT
, // The user did not provide a custom passphrase for encryption.
245 // We implicitly use the GAIA password in such cases.
246 EXPLICIT
, // The user selected the "use custom passphrase" radio button
247 // during sync setup and provided a passphrase.
250 enum SyncStatusSummary
{
254 DATATYPES_NOT_INITIALIZED
,
263 SYNC
, // Backend for syncing.
264 BACKUP
, // Backend for backup.
265 ROLLBACK
// Backend for rollback.
268 // Default sync server URL.
269 static const char* kSyncServerUrl
;
270 // Sync server URL for dev channel users
271 static const char* kDevServerUrl
;
273 // Takes ownership of |factory| and |signin_wrapper|.
275 scoped_ptr
<ProfileSyncComponentsFactory
> factory
,
277 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
278 ProfileOAuth2TokenService
* oauth2_token_service
,
279 browser_sync::ProfileSyncServiceStartBehavior start_behavior
);
280 virtual ~ProfileSyncService();
282 // Initializes the object. This must be called at most once, and
283 // immediately after an object of this class is constructed.
286 virtual void SetSyncSetupCompleted();
288 // ProfileSyncServiceBase implementation.
289 virtual bool HasSyncSetupCompleted() const OVERRIDE
;
290 virtual bool ShouldPushChanges() OVERRIDE
;
291 virtual syncer::ModelTypeSet
GetActiveDataTypes() const OVERRIDE
;
292 virtual void AddObserver(ProfileSyncServiceBase::Observer
* observer
) OVERRIDE
;
293 virtual void RemoveObserver(
294 ProfileSyncServiceBase::Observer
* observer
) OVERRIDE
;
295 virtual bool HasObserver(
296 ProfileSyncServiceBase::Observer
* observer
) const OVERRIDE
;
299 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver
* observer
);
300 void RemoveProtocolEventObserver(
301 browser_sync::ProtocolEventObserver
* observer
);
303 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
304 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
306 // Add a sync type preference provider. Each provider may only be added once.
307 void AddPreferenceProvider(SyncTypePreferenceProvider
* provider
);
308 // Remove a sync type preference provider. May only be called for providers
309 // that have been added. Providers must not remove themselves while being
311 void RemovePreferenceProvider(SyncTypePreferenceProvider
* provider
);
312 // Check whether a given sync type preference provider has been added.
313 bool HasPreferenceProvider(SyncTypePreferenceProvider
* provider
) const;
315 // Asynchronously fetches base::Value representations of all sync nodes and
316 // returns them to the specified callback on this thread.
318 // These requests can live a long time and return when you least expect it.
319 // For safety, the callback should be bound to some sort of WeakPtr<> or
322 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
324 void RegisterAuthNotifications();
325 void UnregisterAuthNotifications();
327 // Returns true if sync is enabled/not suppressed and the user is logged in.
328 // (being logged in does not mean that tokens are available - tokens may
329 // be missing because they have not loaded yet, or because they were deleted
330 // due to http://crbug.com/121755).
331 // Virtual to enable mocking in tests.
332 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
333 // callers use a seemingly arbitrary / redundant / bug prone combination of
334 // this method, IsSyncAccessible, and others.
335 virtual bool IsSyncEnabledAndLoggedIn();
337 // Return whether OAuth2 refresh token is loaded and available for the backend
338 // to start up. Virtual to enable mocking in tests.
339 virtual bool IsOAuthRefreshTokenAvailable();
341 // Registers a data type controller with the sync service. This
342 // makes the data type controller available for use, it does not
343 // enable or activate the synchronization of the data type (see
344 // ActivateDataType). Takes ownership of the pointer.
345 void RegisterDataTypeController(
346 sync_driver::DataTypeController
* data_type_controller
);
348 // Registers a type whose sync storage will not be managed by the
349 // ProfileSyncService. It declares that this sync type may be activated at
350 // some point in the future. This function call does not enable or activate
351 // the syncing of this type
352 void RegisterNonBlockingType(syncer::ModelType type
);
354 // Called by a component that supports non-blocking sync when it is ready to
355 // initialize its connection to the sync backend.
357 // If policy allows for syncing this type (ie. it is "preferred"), then this
358 // should result in a message to enable syncing for this type when the sync
359 // backend is available. If the type is not to be synced, this should result
360 // in a message that allows the component to delete its local sync state.
361 void InitializeNonBlockingType(
362 syncer::ModelType type
,
363 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
364 const base::WeakPtr
<syncer::ModelTypeSyncProxyImpl
>& proxy
);
366 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
367 // currently syncing, returns NULL.
368 virtual browser_sync::OpenTabsUIDelegate
* GetOpenTabsUIDelegate();
370 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
371 virtual browser_sync::SyncedWindowDelegatesGetter
*
372 GetSyncedWindowDelegatesGetter() const;
374 // Returns the SyncableService for syncer::SESSIONS.
375 virtual syncer::SyncableService
* GetSessionsSyncableService();
377 // Returns DeviceInfo provider for the local device.
378 virtual browser_sync::LocalDeviceInfoProvider
* GetLocalDeviceInfoProvider();
380 // Returns sync's representation of the device info for a client identified
381 // by |client_id|. Return value is an empty scoped ptr if the device info
383 virtual scoped_ptr
<browser_sync::DeviceInfo
> GetDeviceInfo(
384 const std::string
& client_id
) const;
386 // Gets the device info for all devices signed into the account associated
387 // with this profile.
388 virtual ScopedVector
<browser_sync::DeviceInfo
> GetAllSignedInDevices() const;
390 // Notifies the observer of any device info changes.
391 virtual void AddObserverForDeviceInfoChange(
392 browser_sync::SyncedDeviceTracker::Observer
* observer
);
394 // Removes the observer from device info notification.
395 virtual void RemoveObserverForDeviceInfoChange(
396 browser_sync::SyncedDeviceTracker::Observer
* observer
);
398 // Fills state_map with a map of current data types that are possible to
399 // sync, as well as their states.
400 void GetDataTypeControllerStates(
401 sync_driver::DataTypeController::StateMap
* state_map
) const;
403 // Disables sync for user. Use ShowLoginDialog to enable.
404 virtual void DisableForUser();
406 // Disables sync for the user and prevents it from starting on next restart.
407 virtual void StopSyncingPermanently();
409 // SyncFrontend implementation.
410 virtual void OnBackendInitialized(
411 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
412 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
414 const std::string
& cache_guid
,
415 bool success
) OVERRIDE
;
416 virtual void OnSyncCycleCompleted() OVERRIDE
;
417 virtual void OnProtocolEvent(const syncer::ProtocolEvent
& event
) OVERRIDE
;
418 virtual void OnDirectoryTypeCommitCounterUpdated(
419 syncer::ModelType type
,
420 const syncer::CommitCounters
& counters
) OVERRIDE
;
421 virtual void OnDirectoryTypeUpdateCounterUpdated(
422 syncer::ModelType type
,
423 const syncer::UpdateCounters
& counters
) OVERRIDE
;
424 virtual void OnDirectoryTypeStatusCounterUpdated(
425 syncer::ModelType type
,
426 const syncer::StatusCounters
& counters
) OVERRIDE
;
427 virtual void OnSyncConfigureRetry() OVERRIDE
;
428 virtual void OnConnectionStatusChange(
429 syncer::ConnectionStatus status
) OVERRIDE
;
430 virtual void OnPassphraseRequired(
431 syncer::PassphraseRequiredReason reason
,
432 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
433 virtual void OnPassphraseAccepted() OVERRIDE
;
434 virtual void OnEncryptedTypesChanged(
435 syncer::ModelTypeSet encrypted_types
,
436 bool encrypt_everything
) OVERRIDE
;
437 virtual void OnEncryptionComplete() OVERRIDE
;
438 virtual void OnMigrationNeededForTypes(
439 syncer::ModelTypeSet types
) OVERRIDE
;
440 virtual void OnExperimentsChanged(
441 const syncer::Experiments
& experiments
) OVERRIDE
;
442 virtual void OnActionableError(
443 const syncer::SyncProtocolError
& error
) OVERRIDE
;
445 // DataTypeManagerObserver implementation.
446 virtual void OnConfigureDone(
447 const sync_driver::DataTypeManager::ConfigureResult
& result
) OVERRIDE
;
448 virtual void OnConfigureRetry() OVERRIDE
;
449 virtual void OnConfigureStart() OVERRIDE
;
451 // DataTypeEncryptionHandler implementation.
452 virtual bool IsPassphraseRequired() const OVERRIDE
;
453 virtual syncer::ModelTypeSet
GetEncryptedDataTypes() const OVERRIDE
;
455 // SigninManagerBase::Observer implementation.
456 virtual void GoogleSigninSucceeded(const std::string
& account_id
,
457 const std::string
& username
,
458 const std::string
& password
) OVERRIDE
;
459 virtual void GoogleSignedOut(const std::string
& account_id
,
460 const std::string
& username
) OVERRIDE
;
462 // Called when a user chooses which data types to sync as part of the sync
463 // setup wizard. |sync_everything| represents whether they chose the
464 // "keep everything synced" option; if true, |chosen_types| will be ignored
465 // and all data types will be synced. |sync_everything| means "sync all
466 // current and future data types."
467 virtual void OnUserChoseDatatypes(bool sync_everything
,
468 syncer::ModelTypeSet chosen_types
);
470 // Get the sync status code.
471 SyncStatusSummary
QuerySyncStatusSummary();
473 // Get a description of the sync status for displaying in the user interface.
474 std::string
QuerySyncStatusSummaryString();
476 // Initializes a struct of status indicators with data from the backend.
477 // Returns false if the backend was not available for querying; in that case
478 // the struct will be filled with default data.
479 virtual bool QueryDetailedSyncStatus(
480 browser_sync::SyncBackendHost::Status
* result
);
482 virtual const GoogleServiceAuthError
& GetAuthError() const;
484 // Returns true if initial sync setup is in progress (does not return true
485 // if the user is customizing sync after already completing setup once).
486 // ProfileSyncService uses this to determine if it's OK to start syncing, or
487 // if the user is still setting up the initial sync configuration.
488 virtual bool FirstSetupInProgress() const;
490 // Called by the UI to notify the ProfileSyncService that UI is visible so it
491 // will not start syncing. This tells sync whether it's safe to start
492 // downloading data types yet (we don't start syncing until after sync setup
493 // is complete). The UI calls this as soon as any part of the signin wizard is
494 // displayed (even just the login UI).
495 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
496 // that data download starts.
497 virtual void SetSetupInProgress(bool setup_in_progress
);
499 // Returns true if the SyncBackendHost has told us it's ready to accept
501 // [REMARK] - it is safe to call this function only from the ui thread.
502 // because the variable is not thread safe and should only be accessed from
503 // single thread. If we want multiple threads to access this(and there is
504 // currently no need to do so) we need to protect this with a lock.
505 // TODO(timsteele): What happens if the bookmark model is loaded, a change
506 // takes place, and the backend isn't initialized yet?
507 virtual bool sync_initialized() const;
509 virtual bool HasUnrecoverableError() const;
510 const std::string
& unrecoverable_error_message() {
511 return unrecoverable_error_message_
;
513 tracked_objects::Location
unrecoverable_error_location() {
514 return unrecoverable_error_location_
;
517 // Returns true if OnPassphraseRequired has been called for decryption and
518 // we have an encrypted data type enabled.
519 virtual bool IsPassphraseRequiredForDecryption() const;
521 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
522 return passphrase_required_reason_
;
525 // Returns a user-friendly string form of last synced time (in minutes).
526 virtual base::string16
GetLastSyncedTimeString() const;
528 // Returns a human readable string describing backend initialization state.
529 std::string
GetBackendInitializationStateString() const;
531 // Returns true if startup is suppressed (i.e. user has stopped syncing via
532 // the google dashboard).
533 virtual bool IsStartSuppressed() const;
535 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
537 // The profile we are syncing for.
538 Profile
* profile() const { return profile_
; }
540 // Returns a weak pointer to the service's JsController.
541 // Overrideable for testing purposes.
542 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
544 // Record stats on various events.
545 static void SyncEvent(SyncEventCodes code
);
547 // Returns whether sync is enabled. Sync can be enabled/disabled both
548 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
549 // command-line switches).
550 // Profile::IsSyncAccessible() is probably a better signal than this function.
551 // This function can be called from any thread, and the implementation doesn't
552 // assume it's running on the UI thread.
553 static bool IsSyncEnabled();
555 // Returns whether sync is managed, i.e. controlled by configuration
556 // management. If so, the user is not allowed to configure sync.
557 virtual bool IsManaged() const;
559 // syncer::UnrecoverableErrorHandler implementation.
560 virtual void OnUnrecoverableError(
561 const tracked_objects::Location
& from_here
,
562 const std::string
& message
) OVERRIDE
;
564 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
565 // not change the preferred state of a datatype, and is not persisted across
567 void ReenableDatatype(syncer::ModelType type
);
569 // The functions below (until ActivateDataType()) should only be
570 // called if sync_initialized() is true.
572 // TODO(akalin): This is called mostly by ModelAssociators and
573 // tests. Figure out how to pass the handle to the ModelAssociators
574 // directly, figure out how to expose this to tests, and remove this
576 virtual syncer::UserShare
* GetUserShare() const;
578 // TODO(akalin): These two functions are used only by
579 // ProfileSyncServiceHarness. Figure out a different way to expose
580 // this info to that class, and remove these functions.
582 virtual syncer::sessions::SyncSessionSnapshot
583 GetLastSessionSnapshot() const;
585 // Returns whether or not the underlying sync engine has made any
586 // local changes to items that have not yet been synced with the
588 bool HasUnsyncedItems() const;
590 // Used by ProfileSyncServiceHarness. May return NULL.
591 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
593 // Used by tests to inspect interaction with OAuth2TokenService.
594 bool IsRetryingAccessTokenFetchForTest() const;
596 // Used by tests to inspect the OAuth2 access tokens used by PSS.
597 std::string
GetAccessTokenForTest() const;
599 // TODO(sync): This is only used in tests. Can we remove it?
600 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
602 // Returns a ListValue indicating the status of all registered types.
605 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
606 // where <name> is a type's name, <value> is a string providing details for
607 // the type's status, and <status> is one of "error", "warning" or "ok"
608 // depending on the type's current status.
610 // This function is used by about_sync_util.cc to help populate the about:sync
611 // page. It returns a ListValue rather than a DictionaryValue in part to make
612 // it easier to iterate over its elements when constructing that page.
613 base::Value
* GetTypeStatusMap() const;
615 // Overridden by tests.
616 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
617 virtual void DeactivateDataType(syncer::ModelType type
);
619 // SyncPrefObserver implementation.
620 virtual void OnSyncManagedPrefChange(bool is_sync_managed
) OVERRIDE
;
622 // Changes which data types we're going to be syncing to |preferred_types|.
623 // If it is running, the DataTypeManager will be instructed to reconfigure
624 // the sync backend so that exactly these datatypes are actively synced. See
625 // class comment for more on what it means for a datatype to be Preferred.
626 virtual void ChangePreferredDataTypes(
627 syncer::ModelTypeSet preferred_types
);
629 // Returns the set of types which are preferred for enabling. This is a
630 // superset of the active types (see GetActiveDataTypes()).
631 virtual syncer::ModelTypeSet
GetPreferredDataTypes() const;
633 // Returns the set of directory types which are preferred for enabling.
634 virtual syncer::ModelTypeSet
GetPreferredDirectoryDataTypes() const;
636 // Returns the set of off-thread types which are preferred for enabling.
637 virtual syncer::ModelTypeSet
GetPreferredNonBlockingDataTypes() const;
639 // Returns the set of types which are enforced programmatically and can not
640 // be disabled by the user.
641 virtual syncer::ModelTypeSet
GetForcedDataTypes() const;
643 // Gets the set of all data types that could be allowed (the set that
644 // should be advertised to the user). These will typically only change
645 // via a command-line option. See class comment for more on what it means
646 // for a datatype to be Registered.
647 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
649 // Gets the set of directory types which could be allowed.
650 virtual syncer::ModelTypeSet
GetRegisteredDirectoryDataTypes() const;
652 // Gets the set of off-thread types which could be allowed.
653 virtual syncer::ModelTypeSet
GetRegisteredNonBlockingDataTypes() const;
655 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
656 // for sensitive data types. Caller must be holding a
657 // syncapi::BaseTransaction to ensure thread safety.
658 virtual bool IsCryptographerReady(
659 const syncer::BaseTransaction
* trans
) const;
661 // Returns true if a secondary (explicit) passphrase is being used. It is not
662 // legal to call this method before the backend is initialized.
663 virtual bool IsUsingSecondaryPassphrase() const;
665 // Returns the actual passphrase type being used for encryption.
666 virtual syncer::PassphraseType
GetPassphraseType() const;
668 // Returns the time the current explicit passphrase (if any), was set.
669 // If no secondary passphrase is in use, or no time is available, returns an
671 virtual base::Time
GetExplicitPassphraseTime() const;
673 // Note about setting passphrases: There are different scenarios under which
674 // we might want to apply a passphrase. It could be for first-time encryption,
675 // re-encryption, or for decryption by clients that sign in at a later time.
676 // In addition, encryption can either be done using a custom passphrase, or by
677 // reusing the GAIA password. Depending on what is happening in the system,
678 // callers should determine which of the two methods below must be used.
680 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
681 // specifies whether the passphrase is a custom passphrase or the GAIA
682 // password being reused as a passphrase.
683 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
684 // passphrase with this API.
685 virtual void SetEncryptionPassphrase(const std::string
& passphrase
,
686 PassphraseType type
);
688 // Asynchronously decrypts pending keys using |passphrase|. Returns false
689 // immediately if the passphrase could not be used to decrypt a locally cached
690 // copy of encrypted keys; returns true otherwise.
691 virtual bool SetDecryptionPassphrase(const std::string
& passphrase
)
694 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
695 // after calling this to force the encryption to occur.
696 virtual void EnableEncryptEverything();
698 // Returns true if we are currently set to encrypt all the sync data. Note:
699 // this is based on the cryptographer's settings, so if the user has recently
700 // requested encryption to be turned on, this may not be true yet. For that,
701 // encryption_pending() must be checked.
702 virtual bool EncryptEverythingEnabled() const;
704 // Returns true if the syncer is waiting for new datatypes to be encrypted.
705 virtual bool encryption_pending() const;
707 const GURL
& sync_service_url() const { return sync_service_url_
; }
708 SigninManagerBase
* signin() const;
711 bool auto_start_enabled() const;
712 bool setup_in_progress() const;
714 // Stops the sync backend and sets the flag for suppressing sync startup.
715 void StopAndSuppress();
717 // Resets the flag for suppressing sync startup and starts the sync backend.
718 virtual void UnsuppressAndStart();
720 // Marks all currently registered types as "acknowledged" so we won't prompt
721 // the user about them any more.
722 void AcknowledgeSyncedTypes();
724 SyncErrorController
* sync_error_controller() {
725 return sync_error_controller_
.get();
728 // TODO(sync): This is only used in tests. Can we remove it?
729 const sync_driver::DataTypeStatusTable
& data_type_status_table() const;
731 sync_driver::DataTypeManager::ConfigureStatus
configure_status() {
732 return configure_status_
;
735 // If true, the ProfileSyncService has detected that a new GAIA signin has
736 // succeeded, and is waiting for initialization to complete. This is used by
737 // the UI to differentiate between a new auth error (encountered as part of
738 // the initialization process) and a pre-existing auth error that just hasn't
739 // been cleared yet. Virtual for testing purposes.
740 virtual bool waiting_for_auth() const;
742 // The set of currently enabled sync experiments.
743 const syncer::Experiments
& current_experiments() const;
745 // OAuth2TokenService::Consumer implementation.
746 virtual void OnGetTokenSuccess(
747 const OAuth2TokenService::Request
* request
,
748 const std::string
& access_token
,
749 const base::Time
& expiration_time
) OVERRIDE
;
750 virtual void OnGetTokenFailure(
751 const OAuth2TokenService::Request
* request
,
752 const GoogleServiceAuthError
& error
) OVERRIDE
;
754 // OAuth2TokenService::Observer implementation.
755 virtual void OnRefreshTokenAvailable(const std::string
& account_id
) OVERRIDE
;
756 virtual void OnRefreshTokenRevoked(const std::string
& account_id
) OVERRIDE
;
757 virtual void OnRefreshTokensLoaded() OVERRIDE
;
759 // KeyedService implementation. This must be called exactly
760 // once (before this object is destroyed).
761 virtual void Shutdown() OVERRIDE
;
763 // Called when a datatype (SyncableService) has a need for sync to start
764 // ASAP, presumably because a local change event has occurred but we're
765 // still in deferred start mode, meaning the SyncableService hasn't been
766 // told to MergeDataAndStartSyncing yet.
767 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
);
769 // Return sync token status.
770 SyncTokenStatus
GetSyncTokenStatus() const;
772 browser_sync::FaviconCache
* GetFaviconCache();
774 // Overrides the NetworkResources used for Sync connections.
775 // This function takes ownership of |network_resources|.
776 void OverrideNetworkResourcesForTest(
777 scoped_ptr
<syncer::NetworkResources
> network_resources
);
779 virtual bool IsSessionsDataTypeControllerRunning() const;
781 BackendMode
backend_mode() const {
782 return backend_mode_
;
785 // Helpers for testing rollback.
786 void SetBrowsingDataRemoverObserverForTesting(
787 BrowsingDataRemover::Observer
* observer
);
788 void SetClearingBrowseringDataForTesting(base::Callback
<
789 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
792 // Return the base URL of the Sync Server.
793 static GURL
GetSyncServiceURL(const base::CommandLine
& command_line
);
795 base::Time
GetDeviceBackupTimeForTesting() const;
798 // Helper to configure the priority data types.
799 void ConfigurePriorityDataTypes();
801 // Helper to install and configure a data type manager.
802 void ConfigureDataTypeManager();
804 // Shuts down the backend sync components.
805 // |reason| dictates if syncing is being disabled or not, and whether
806 // to claim ownership of sync thread from backend.
807 void ShutdownImpl(syncer::ShutdownReason reason
);
809 // Return SyncCredentials from the OAuth2TokenService.
810 syncer::SyncCredentials
GetCredentials();
812 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
814 const sync_driver::DataTypeController::TypeMap
&
815 directory_data_type_controllers() {
816 return directory_data_type_controllers_
;
819 // Helper method for managing encryption UI.
820 bool IsEncryptedDatatypeEnabled() const;
822 // Helper for OnUnrecoverableError.
823 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
824 // and in SyncBackendHost::Shutdown.
825 void OnUnrecoverableErrorImpl(
826 const tracked_objects::Location
& from_here
,
827 const std::string
& message
,
828 bool delete_sync_database
);
830 virtual bool NeedBackup() const;
832 // This is a cache of the last authentication response we received from the
833 // sync server. The UI queries this to display appropriate messaging to the
835 GoogleServiceAuthError last_auth_error_
;
837 // Our asynchronous backend to communicate with sync components living on
839 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
841 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
842 // was required for encryption, decryption with a cached passphrase, or
843 // because a new passphrase is required?
844 syncer::PassphraseRequiredReason passphrase_required_reason_
;
847 enum UnrecoverableErrorReason
{
850 ERROR_REASON_BACKEND_INIT_FAILURE
,
851 ERROR_REASON_CONFIGURATION_RETRY
,
852 ERROR_REASON_CONFIGURATION_FAILURE
,
853 ERROR_REASON_ACTIONABLE_ERROR
,
857 enum AuthErrorMetric
{
858 AUTH_ERROR_ENCOUNTERED
,
863 friend class ProfileSyncServicePasswordTest
;
864 friend class SyncTest
;
865 friend class TestProfileSyncService
;
866 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
868 // Update the last auth error and notify observers of error state.
869 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
871 // Detects and attempts to recover from a previous improper datatype
872 // configuration where Keep Everything Synced and the preferred types were
873 // not correctly set.
874 void TrySyncDatatypePrefRecovery();
876 // Puts the backend's sync scheduler into NORMAL mode.
877 // Called when configuration is complete.
878 void StartSyncingWithServer();
880 // Called when we've determined that we don't need a passphrase (either
881 // because OnPassphraseAccepted() was called, or because we've gotten a
882 // OnPassphraseRequired() but no data types are enabled).
883 void ResolvePassphraseRequired();
885 // During initial signin, ProfileSyncService caches the user's signin
886 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
887 // This routine is invoked once the backend has started up to use the
888 // cached passphrase and clear it out when it is done.
889 void ConsumeCachedPassphraseIfPossible();
891 // RequestAccessToken initiates RPC to request downscoped access token from
892 // refresh token. This happens when a new OAuth2 login token is loaded and
893 // when sync server returns AUTH_ERROR which indicates it is time to refresh
895 virtual void RequestAccessToken();
897 // Return true if backend should start from a fresh sync DB.
898 bool ShouldDeleteSyncFolder();
900 // If |delete_sync_data_folder| is true, then this method will delete all
901 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
902 void InitializeBackend(bool delete_sync_data_folder
);
904 // Initializes the various settings from the command line.
907 // Sets the last synced time to the current time.
908 void UpdateLastSyncedTime();
910 void NotifyObservers();
911 void NotifySyncCycleCompleted();
913 void ClearStaleErrors();
915 void ClearUnrecoverableError();
917 // Starts up the backend sync components. |mode| specifies the kind of
918 // backend to start, one of SYNC, BACKUP or ROLLBACK.
919 virtual void StartUpSlowBackendComponents(BackendMode mode
);
921 // About-flags experiment names for datatypes that aren't enabled by default
923 static std::string
GetExperimentNameForDataType(
924 syncer::ModelType data_type
);
926 // Create and register a new datatype controller.
927 void RegisterNewDataType(syncer::ModelType data_type
);
929 // Reconfigures the data type manager with the latest enabled types.
930 // Note: Does not initialize the backend if it is not already initialized.
931 // This function needs to be called only after sync has been initialized
932 // (i.e.,only for reconfigurations). The reason we don't initialize the
933 // backend is because if we had encountered an unrecoverable error we don't
934 // want to startup once more.
935 virtual void ReconfigureDatatypeManager();
937 // Collects preferred sync data types from |preference_providers_|.
938 syncer::ModelTypeSet
GetDataTypesFromPreferenceProviders() const;
940 // Called when the user changes the sync configuration, to update the UMA
942 void UpdateSelectedTypesHistogram(
943 bool sync_everything
,
944 const syncer::ModelTypeSet chosen_types
) const;
946 #if defined(OS_CHROMEOS)
947 // Refresh spare sync bootstrap token for re-enabling the sync service.
948 // Called on successful sign-in notifications.
949 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
952 // Internal unrecoverable error handler. Used to track error reason via
953 // Sync.UnrecoverableErrors histogram.
954 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
955 const std::string
& message
,
956 bool delete_sync_database
,
957 UnrecoverableErrorReason reason
);
959 // Returns the type of manager to use according to |backend_mode_|.
960 syncer::SyncManagerFactory::MANAGER_TYPE
GetManagerType() const;
962 // Update UMA for syncing backend.
963 void UpdateBackendInitUMA(bool success
);
965 // Various setup following backend initialization, mostly for syncing backend.
966 void PostBackendInitialization();
968 // True if a syncing backend exists.
969 bool HasSyncingBackend() const;
971 // Update first sync time stored in preferences
972 void UpdateFirstSyncTimePref();
974 // Clear browsing data since first sync during rollback.
975 void ClearBrowsingDataSinceFirstSync();
977 // Post background task to check sync backup DB state if needed.
978 void CheckSyncBackupIfNeeded();
980 // Callback to receive backup DB check result.
981 void CheckSyncBackupCallback(base::Time backup_time
);
983 // Callback function to call |startup_controller_|.TryStart() after
984 // backup/rollback finishes;
985 void TryStartSyncAfterBackup();
987 // Clean up prefs and backup DB when rollback is not needed.
988 void CleanUpBackup();
990 // Factory used to create various dependent objects.
991 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
993 // The profile whose data we are synchronizing.
996 // The class that handles getting, setting, and persisting sync
998 sync_driver::SyncPrefs sync_prefs_
;
1000 // TODO(ncarter): Put this in a profile, once there is UI for it.
1001 // This specifies where to find the sync server.
1002 const GURL sync_service_url_
;
1004 // The last time we detected a successful transition from SYNCING state.
1005 // Our backend notifies us whenever we should take a new snapshot.
1006 base::Time last_synced_time_
;
1008 // The time that OnConfigureStart is called. This member is zero if
1009 // OnConfigureStart has not yet been called, and is reset to zero once
1010 // OnConfigureDone is called.
1011 base::Time sync_configure_start_time_
;
1013 // Indicates if this is the first time sync is being configured. This value
1014 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
1015 bool is_first_time_sync_configure_
;
1017 // List of available data type controllers for directory types.
1018 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_
;
1020 // Whether the SyncBackendHost has been initialized.
1021 bool backend_initialized_
;
1023 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1024 // ProfileSyncService from starting backend till browser restarted or user
1026 bool sync_disabled_by_admin_
;
1028 // Set to true if a signin has completed but we're still waiting for the
1029 // backend to refresh its credentials.
1030 bool is_auth_in_progress_
;
1032 // Encapsulates user signin - used to set/get the user's authenticated
1034 const scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_
;
1036 // Information describing an unrecoverable error.
1037 UnrecoverableErrorReason unrecoverable_error_reason_
;
1038 std::string unrecoverable_error_message_
;
1039 tracked_objects::Location unrecoverable_error_location_
;
1041 // Manages the start and stop of the directory data types.
1042 scoped_ptr
<sync_driver::DataTypeManager
> directory_data_type_manager_
;
1044 // Manager for the non-blocking data types.
1045 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_
;
1047 ObserverList
<ProfileSyncServiceBase::Observer
> observers_
;
1048 ObserverList
<browser_sync::ProtocolEventObserver
> protocol_event_observers_
;
1049 ObserverList
<syncer::TypeDebugInfoObserver
> type_debug_info_observers_
;
1051 std::set
<SyncTypePreferenceProvider
*> preference_providers_
;
1053 syncer::SyncJsController sync_js_controller_
;
1055 // This allows us to gracefully handle an ABORTED return code from the
1056 // DataTypeManager in the event that the server informed us to cease and
1057 // desist syncing immediately.
1058 bool expect_sync_configuration_aborted_
;
1060 // Sometimes we need to temporarily hold on to a passphrase because we don't
1061 // yet have a backend to send it to. This happens during initialization as
1062 // we don't StartUp until we have a valid token, which happens after valid
1063 // credentials were provided.
1064 std::string cached_passphrase_
;
1066 // The current set of encrypted types. Always a superset of
1067 // syncer::Cryptographer::SensitiveTypes().
1068 syncer::ModelTypeSet encrypted_types_
;
1070 // Whether we want to encrypt everything.
1071 bool encrypt_everything_
;
1073 // Whether we're waiting for an attempt to encryption all sync data to
1074 // complete. We track this at this layer in order to allow the user to cancel
1075 // if they e.g. don't remember their explicit passphrase.
1076 bool encryption_pending_
;
1078 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
1080 // This is the last |SyncProtocolError| we received from the server that had
1081 // an action set on it.
1082 syncer::SyncProtocolError last_actionable_error_
;
1084 // Exposes sync errors to the UI.
1085 scoped_ptr
<SyncErrorController
> sync_error_controller_
;
1087 // Tracks the set of failed data types (those that encounter an error
1088 // or must delay loading for some reason).
1089 sync_driver::DataTypeStatusTable data_type_status_table_
;
1091 sync_driver::DataTypeManager::ConfigureStatus configure_status_
;
1093 // The set of currently enabled sync experiments.
1094 syncer::Experiments current_experiments_
;
1096 // Sync's internal debug info listener. Used to record datatype configuration
1097 // and association information.
1098 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
1100 // A thread where all the sync operations happen.
1102 // * Created when backend starts for the first time.
1103 // * If sync is disabled, PSS claims ownership from backend.
1104 // * If sync is reenabled, PSS passes ownership to new backend.
1105 scoped_ptr
<base::Thread
> sync_thread_
;
1107 // ProfileSyncService uses this service to get access tokens.
1108 ProfileOAuth2TokenService
* const oauth2_token_service_
;
1110 // ProfileSyncService needs to remember access token in order to invalidate it
1111 // with OAuth2TokenService.
1112 std::string access_token_
;
1114 // ProfileSyncService needs to hold reference to access_token_request_ for
1115 // the duration of request in order to receive callbacks.
1116 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
1118 // If RequestAccessToken fails with transient error then retry requesting
1119 // access token with exponential backoff.
1120 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
1121 net::BackoffEntry request_access_token_backoff_
;
1123 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
1125 // We don't use |weak_factory_| for the StartupController because the weak
1126 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1127 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1128 // StartupController an Unretained reference to future-proof against
1129 // the controller impl changing to post tasks. Therefore, we have a separate
1131 base::WeakPtrFactory
<ProfileSyncService
> startup_controller_weak_factory_
;
1133 // States related to sync token and connection.
1134 base::Time connection_status_update_time_
;
1135 syncer::ConnectionStatus connection_status_
;
1136 base::Time token_request_time_
;
1137 base::Time token_receive_time_
;
1138 GoogleServiceAuthError last_get_token_error_
;
1139 base::Time next_token_request_time_
;
1141 scoped_ptr
<LocalDeviceInfoProvider
> local_device_
;
1143 // Locally owned SyncableService implementations.
1144 scoped_ptr
<SessionsSyncManager
> sessions_sync_manager_
;
1146 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
1148 browser_sync::StartupController startup_controller_
;
1150 browser_sync::BackupRollbackController backup_rollback_controller_
;
1152 // Mode of current backend.
1153 BackendMode backend_mode_
;
1155 // Whether backup is needed before sync starts.
1158 // Whether backup is finished.
1159 bool backup_finished_
;
1161 base::Time backup_start_time_
;
1164 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
1165 clear_browsing_data_
;
1167 // Last time when pre-sync data was saved. NULL pointer means backup data
1168 // state is unknown. If time value is null, backup data doesn't exist.
1169 scoped_ptr
<base::Time
> last_backup_time_
;
1171 BrowsingDataRemover::Observer
* browsing_data_remover_observer_
;
1173 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1176 bool ShouldShowActionOnUI(
1177 const syncer::SyncProtocolError
& error
);
1180 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_