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/files/file_path.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/strings/string16.h"
22 #include "base/time/time.h"
23 #include "base/timer/timer.h"
24 #include "chrome/browser/browsing_data/browsing_data_remover.h"
25 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
26 #include "chrome/browser/sync/backup_rollback_controller.h"
27 #include "chrome/browser/sync/glue/sync_backend_host.h"
28 #include "chrome/browser/sync/profile_sync_service_base.h"
29 #include "chrome/browser/sync/profile_sync_service_observer.h"
30 #include "chrome/browser/sync/protocol_event_observer.h"
31 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
32 #include "chrome/browser/sync/startup_controller.h"
33 #include "chrome/browser/sync/sync_stopped_reporter.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/device_info_sync_service.h"
42 #include "components/sync_driver/local_device_info_provider.h"
43 #include "components/sync_driver/non_blocking_data_type_manager.h"
44 #include "components/sync_driver/sync_frontend.h"
45 #include "components/sync_driver/sync_prefs.h"
46 #include "google_apis/gaia/google_service_auth_error.h"
47 #include "google_apis/gaia/oauth2_token_service.h"
48 #include "net/base/backoff_entry.h"
49 #include "sync/internal_api/public/base/model_type.h"
50 #include "sync/internal_api/public/engine/model_safe_worker.h"
51 #include "sync/internal_api/public/shutdown_reason.h"
52 #include "sync/internal_api/public/sync_manager_factory.h"
53 #include "sync/internal_api/public/util/experiments.h"
54 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
55 #include "sync/js/sync_js_controller.h"
59 class ProfileOAuth2TokenService
;
60 class ProfileSyncComponentsFactory
;
61 class SupervisedUserSigninManagerWrapper
;
62 class SyncErrorController
;
63 class SyncTypePreferenceProvider
;
69 namespace browser_sync
{
70 class BackendMigrator
;
73 class OpenTabsUIDelegate
;
76 class SyncSessionSnapshot
;
77 } // namespace sessions
78 } // namespace browser_sync
80 namespace sync_driver
{
81 class ChangeProcessor
;
82 class DataTypeManager
;
83 class DeviceInfoSyncService
;
84 class LocalDeviceInfoProvider
;
85 } // namespace sync_driver
88 class BaseTransaction
;
89 class NetworkResources
;
90 struct CommitCounters
;
91 struct StatusCounters
;
92 struct SyncCredentials
;
93 struct UpdateCounters
;
99 } // namespace sync_pb
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 ~ProfileSyncService() override
;
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 bool HasSyncSetupCompleted() const override
;
290 bool SyncActive() const override
;
291 syncer::ModelTypeSet
GetActiveDataTypes() const override
;
292 void AddObserver(ProfileSyncServiceBase::Observer
* observer
) override
;
293 void RemoveObserver(ProfileSyncServiceBase::Observer
* observer
) override
;
295 const ProfileSyncServiceBase::Observer
* observer
) const override
;
297 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver
* observer
);
298 void RemoveProtocolEventObserver(
299 browser_sync::ProtocolEventObserver
* observer
);
301 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
302 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
304 // Add a sync type preference provider. Each provider may only be added once.
305 void AddPreferenceProvider(SyncTypePreferenceProvider
* provider
);
306 // Remove a sync type preference provider. May only be called for providers
307 // that have been added. Providers must not remove themselves while being
309 void RemovePreferenceProvider(SyncTypePreferenceProvider
* provider
);
310 // Check whether a given sync type preference provider has been added.
311 bool HasPreferenceProvider(SyncTypePreferenceProvider
* provider
) const;
313 // Asynchronously fetches base::Value representations of all sync nodes and
314 // returns them to the specified callback on this thread.
316 // These requests can live a long time and return when you least expect it.
317 // For safety, the callback should be bound to some sort of WeakPtr<> or
320 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
322 void RegisterAuthNotifications();
323 void UnregisterAuthNotifications();
325 // Returns true if sync is enabled/not suppressed and the user is logged in.
326 // (being logged in does not mean that tokens are available - tokens may
327 // be missing because they have not loaded yet, or because they were deleted
328 // due to http://crbug.com/121755).
329 // Virtual to enable mocking in tests.
330 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
331 // callers use a seemingly arbitrary / redundant / bug prone combination of
332 // this method, IsSyncAccessible, and others.
333 virtual bool IsSyncEnabledAndLoggedIn();
335 // Return whether OAuth2 refresh token is loaded and available for the backend
336 // to start up. Virtual to enable mocking in tests.
337 virtual bool IsOAuthRefreshTokenAvailable();
339 // Registers a data type controller with the sync service. This
340 // makes the data type controller available for use, it does not
341 // enable or activate the synchronization of the data type (see
342 // ActivateDataType). Takes ownership of the pointer.
343 void RegisterDataTypeController(
344 sync_driver::DataTypeController
* data_type_controller
);
346 // Registers a type whose sync storage will not be managed by the
347 // ProfileSyncService. It declares that this sync type may be activated at
348 // some point in the future. This function call does not enable or activate
349 // the syncing of this type
350 void RegisterNonBlockingType(syncer::ModelType type
);
352 // Called by a component that supports non-blocking sync when it is ready to
353 // initialize its connection to the sync backend.
355 // If policy allows for syncing this type (ie. it is "preferred"), then this
356 // should result in a message to enable syncing for this type when the sync
357 // backend is available. If the type is not to be synced, this should result
358 // in a message that allows the component to delete its local sync state.
359 void InitializeNonBlockingType(
360 syncer::ModelType type
,
361 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
362 const base::WeakPtr
<syncer::ModelTypeSyncProxyImpl
>& proxy
);
364 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
365 // currently syncing, returns NULL.
366 virtual browser_sync::OpenTabsUIDelegate
* GetOpenTabsUIDelegate();
368 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
369 virtual browser_sync::SyncedWindowDelegatesGetter
*
370 GetSyncedWindowDelegatesGetter() const;
372 // Returns the SyncableService for syncer::SESSIONS.
373 virtual syncer::SyncableService
* GetSessionsSyncableService();
375 // Returns the SyncableService for syncer::DEVICE_INFO.
376 virtual syncer::SyncableService
* GetDeviceInfoSyncableService();
378 // Returns DeviceInfo provider for the local device.
379 virtual sync_driver::LocalDeviceInfoProvider
* GetLocalDeviceInfoProvider();
381 // Returns synced devices tracker.
382 virtual sync_driver::DeviceInfoTracker
* GetDeviceInfoTracker() const;
384 // Fills state_map with a map of current data types that are possible to
385 // sync, as well as their states.
386 void GetDataTypeControllerStates(
387 sync_driver::DataTypeController::StateMap
* state_map
) const;
389 // Disables sync for user. Use ShowLoginDialog to enable.
390 virtual void DisableForUser();
392 // Disables sync for the user and prevents it from starting on next restart.
393 virtual void StopSyncingPermanently();
395 // SyncFrontend implementation.
396 void OnBackendInitialized(
397 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
398 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
400 const std::string
& cache_guid
,
401 bool success
) override
;
402 void OnSyncCycleCompleted() override
;
403 void OnProtocolEvent(const syncer::ProtocolEvent
& event
) override
;
404 void OnDirectoryTypeCommitCounterUpdated(
405 syncer::ModelType type
,
406 const syncer::CommitCounters
& counters
) override
;
407 void OnDirectoryTypeUpdateCounterUpdated(
408 syncer::ModelType type
,
409 const syncer::UpdateCounters
& counters
) override
;
410 void OnDirectoryTypeStatusCounterUpdated(
411 syncer::ModelType type
,
412 const syncer::StatusCounters
& counters
) override
;
413 void OnConnectionStatusChange(syncer::ConnectionStatus status
) override
;
414 void OnPassphraseRequired(
415 syncer::PassphraseRequiredReason reason
,
416 const sync_pb::EncryptedData
& pending_keys
) override
;
417 void OnPassphraseAccepted() override
;
418 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types
,
419 bool encrypt_everything
) override
;
420 void OnEncryptionComplete() override
;
421 void OnMigrationNeededForTypes(syncer::ModelTypeSet types
) override
;
422 void OnExperimentsChanged(const syncer::Experiments
& experiments
) override
;
423 void OnActionableError(const syncer::SyncProtocolError
& error
) override
;
425 // DataTypeManagerObserver implementation.
426 void OnConfigureDone(
427 const sync_driver::DataTypeManager::ConfigureResult
& result
) override
;
428 void OnConfigureStart() override
;
430 // DataTypeEncryptionHandler implementation.
431 bool IsPassphraseRequired() const override
;
432 syncer::ModelTypeSet
GetEncryptedDataTypes() const override
;
434 // SigninManagerBase::Observer implementation.
435 void GoogleSigninSucceeded(const std::string
& account_id
,
436 const std::string
& username
,
437 const std::string
& password
) override
;
438 void GoogleSignedOut(const std::string
& account_id
,
439 const std::string
& username
) override
;
441 // Called when a user chooses which data types to sync as part of the sync
442 // setup wizard. |sync_everything| represents whether they chose the
443 // "keep everything synced" option; if true, |chosen_types| will be ignored
444 // and all data types will be synced. |sync_everything| means "sync all
445 // current and future data types."
446 virtual void OnUserChoseDatatypes(bool sync_everything
,
447 syncer::ModelTypeSet chosen_types
);
449 // Get the sync status code.
450 SyncStatusSummary
QuerySyncStatusSummary();
452 // Get a description of the sync status for displaying in the user interface.
453 std::string
QuerySyncStatusSummaryString();
455 // Initializes a struct of status indicators with data from the backend.
456 // Returns false if the backend was not available for querying; in that case
457 // the struct will be filled with default data.
458 virtual bool QueryDetailedSyncStatus(
459 browser_sync::SyncBackendHost::Status
* result
);
461 virtual const GoogleServiceAuthError
& GetAuthError() const;
463 // Returns true if initial sync setup is in progress (does not return true
464 // if the user is customizing sync after already completing setup once).
465 // ProfileSyncService uses this to determine if it's OK to start syncing, or
466 // if the user is still setting up the initial sync configuration.
467 virtual bool FirstSetupInProgress() const;
469 // Called by the UI to notify the ProfileSyncService that UI is visible so it
470 // will not start syncing. This tells sync whether it's safe to start
471 // downloading data types yet (we don't start syncing until after sync setup
472 // is complete). The UI calls this as soon as any part of the signin wizard is
473 // displayed (even just the login UI).
474 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
475 // that data download starts. In this case, |ReconfigureDatatypeManager| will
477 virtual void SetSetupInProgress(bool setup_in_progress
);
479 // Reconfigures the data type manager with the latest enabled types.
480 // Note: Does not initialize the backend if it is not already initialized.
481 // This function needs to be called only after sync has been initialized
482 // (i.e.,only for reconfigurations). The reason we don't initialize the
483 // backend is because if we had encountered an unrecoverable error we don't
484 // want to startup once more.
485 // This function is called by |SetSetupInProgress|.
486 virtual void ReconfigureDatatypeManager();
488 virtual bool HasUnrecoverableError() const;
489 const std::string
& unrecoverable_error_message() {
490 return unrecoverable_error_message_
;
492 tracked_objects::Location
unrecoverable_error_location() {
493 return unrecoverable_error_location_
;
496 // Returns true if OnPassphraseRequired has been called for decryption and
497 // we have an encrypted data type enabled.
498 virtual bool IsPassphraseRequiredForDecryption() const;
500 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
501 return passphrase_required_reason_
;
504 // Returns a user-friendly string form of last synced time (in minutes).
505 virtual base::string16
GetLastSyncedTimeString() const;
507 // Returns a human readable string describing backend initialization state.
508 std::string
GetBackendInitializationStateString() const;
510 // Returns true if startup is suppressed (i.e. user has stopped syncing via
511 // the google dashboard).
512 virtual bool IsStartSuppressed() const;
514 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
516 // The profile we are syncing for.
517 Profile
* profile() const { return profile_
; }
519 // Returns a weak pointer to the service's JsController.
520 // Overrideable for testing purposes.
521 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
523 // Record stats on various events.
524 static void SyncEvent(SyncEventCodes code
);
526 // Returns whether sync is enabled. Sync can be enabled/disabled both
527 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
528 // command-line switches).
529 // Profile::IsSyncAccessible() is probably a better signal than this function.
530 // This function can be called from any thread, and the implementation doesn't
531 // assume it's running on the UI thread.
532 static bool IsSyncEnabled();
534 // Returns whether sync is managed, i.e. controlled by configuration
535 // management. If so, the user is not allowed to configure sync.
536 virtual bool IsManaged() const;
538 // syncer::UnrecoverableErrorHandler implementation.
539 void OnUnrecoverableError(const tracked_objects::Location
& from_here
,
540 const std::string
& message
) override
;
542 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
543 // not change the preferred state of a datatype, and is not persisted across
545 void ReenableDatatype(syncer::ModelType type
);
547 // The functions below (until ActivateDataType()) should only be
548 // called if backend_initialized() is true.
550 // TODO(akalin): This is called mostly by ModelAssociators and
551 // tests. Figure out how to pass the handle to the ModelAssociators
552 // directly, figure out how to expose this to tests, and remove this
554 virtual syncer::UserShare
* GetUserShare() const;
556 // TODO(akalin): These two functions are used only by
557 // ProfileSyncServiceHarness. Figure out a different way to expose
558 // this info to that class, and remove these functions.
560 virtual syncer::sessions::SyncSessionSnapshot
561 GetLastSessionSnapshot() const;
563 // Returns whether or not the underlying sync engine has made any
564 // local changes to items that have not yet been synced with the
566 bool HasUnsyncedItems() const;
568 // Used by ProfileSyncServiceHarness. May return NULL.
569 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
571 // Used by tests to inspect interaction with OAuth2TokenService.
572 bool IsRetryingAccessTokenFetchForTest() const;
574 // Used by tests to inspect the OAuth2 access tokens used by PSS.
575 std::string
GetAccessTokenForTest() const;
577 // TODO(sync): This is only used in tests. Can we remove it?
578 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
580 // Returns a ListValue indicating the status of all registered types.
583 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
584 // where <name> is a type's name, <value> is a string providing details for
585 // the type's status, and <status> is one of "error", "warning" or "ok"
586 // depending on the type's current status.
588 // This function is used by about_sync_util.cc to help populate the about:sync
589 // page. It returns a ListValue rather than a DictionaryValue in part to make
590 // it easier to iterate over its elements when constructing that page.
591 base::Value
* GetTypeStatusMap() const;
593 // Overridden by tests.
594 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
595 virtual void DeactivateDataType(syncer::ModelType type
);
597 // SyncPrefObserver implementation.
598 void OnSyncManagedPrefChange(bool is_sync_managed
) override
;
600 // Changes which data types we're going to be syncing to |preferred_types|.
601 // If it is running, the DataTypeManager will be instructed to reconfigure
602 // the sync backend so that exactly these datatypes are actively synced. See
603 // class comment for more on what it means for a datatype to be Preferred.
604 virtual void ChangePreferredDataTypes(
605 syncer::ModelTypeSet preferred_types
);
607 // Returns the set of types which are preferred for enabling. This is a
608 // superset of the active types (see GetActiveDataTypes()).
609 virtual syncer::ModelTypeSet
GetPreferredDataTypes() const;
611 // Returns the set of directory types which are preferred for enabling.
612 virtual syncer::ModelTypeSet
GetPreferredDirectoryDataTypes() const;
614 // Returns the set of off-thread types which are preferred for enabling.
615 virtual syncer::ModelTypeSet
GetPreferredNonBlockingDataTypes() const;
617 // Returns the set of types which are enforced programmatically and can not
618 // be disabled by the user.
619 virtual syncer::ModelTypeSet
GetForcedDataTypes() const;
621 // Gets the set of all data types that could be allowed (the set that
622 // should be advertised to the user). These will typically only change
623 // via a command-line option. See class comment for more on what it means
624 // for a datatype to be Registered.
625 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
627 // Gets the set of directory types which could be allowed.
628 virtual syncer::ModelTypeSet
GetRegisteredDirectoryDataTypes() const;
630 // Gets the set of off-thread types which could be allowed.
631 virtual syncer::ModelTypeSet
GetRegisteredNonBlockingDataTypes() const;
633 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
634 // for sensitive data types. Caller must be holding a
635 // syncapi::BaseTransaction to ensure thread safety.
636 virtual bool IsCryptographerReady(
637 const syncer::BaseTransaction
* trans
) const;
639 // Returns true if a secondary (explicit) passphrase is being used. It is not
640 // legal to call this method before the backend is initialized.
641 virtual bool IsUsingSecondaryPassphrase() const;
643 // Returns the actual passphrase type being used for encryption.
644 virtual syncer::PassphraseType
GetPassphraseType() const;
646 // Returns the time the current explicit passphrase (if any), was set.
647 // If no secondary passphrase is in use, or no time is available, returns an
649 virtual base::Time
GetExplicitPassphraseTime() const;
651 // Note about setting passphrases: There are different scenarios under which
652 // we might want to apply a passphrase. It could be for first-time encryption,
653 // re-encryption, or for decryption by clients that sign in at a later time.
654 // In addition, encryption can either be done using a custom passphrase, or by
655 // reusing the GAIA password. Depending on what is happening in the system,
656 // callers should determine which of the two methods below must be used.
658 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
659 // specifies whether the passphrase is a custom passphrase or the GAIA
660 // password being reused as a passphrase.
661 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
662 // passphrase with this API.
663 virtual void SetEncryptionPassphrase(const std::string
& passphrase
,
664 PassphraseType type
);
666 // Asynchronously decrypts pending keys using |passphrase|. Returns false
667 // immediately if the passphrase could not be used to decrypt a locally cached
668 // copy of encrypted keys; returns true otherwise.
669 virtual bool SetDecryptionPassphrase(const std::string
& passphrase
)
672 // Returns true if encrypting all the sync data is allowed. If this method
673 // returns false, EnableEncryptEverything() should not be called.
674 virtual bool EncryptEverythingAllowed() const;
676 // Sets whether encrypting all the sync data is allowed or not.
677 virtual void SetEncryptEverythingAllowed(bool allowed
);
679 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
680 // after calling this to force the encryption to occur.
681 virtual void EnableEncryptEverything();
683 // Returns true if we are currently set to encrypt all the sync data. Note:
684 // this is based on the cryptographer's settings, so if the user has recently
685 // requested encryption to be turned on, this may not be true yet. For that,
686 // encryption_pending() must be checked.
687 virtual bool EncryptEverythingEnabled() const;
689 // Returns true if the syncer is waiting for new datatypes to be encrypted.
690 virtual bool encryption_pending() const;
692 const GURL
& sync_service_url() const { return sync_service_url_
; }
693 SigninManagerBase
* signin() const;
696 bool auto_start_enabled() const;
697 bool setup_in_progress() const;
699 // Stops the sync backend and sets the flag for suppressing sync startup.
700 void StopAndSuppress();
702 // Resets the flag for suppressing sync startup and starts the sync backend.
703 virtual void UnsuppressAndStart();
705 SyncErrorController
* sync_error_controller() {
706 return sync_error_controller_
.get();
709 // TODO(sync): This is only used in tests. Can we remove it?
710 const sync_driver::DataTypeStatusTable
& data_type_status_table() const;
712 sync_driver::DataTypeManager::ConfigureStatus
configure_status() {
713 return configure_status_
;
716 // If true, the ProfileSyncService has detected that a new GAIA signin has
717 // succeeded, and is waiting for initialization to complete. This is used by
718 // the UI to differentiate between a new auth error (encountered as part of
719 // the initialization process) and a pre-existing auth error that just hasn't
720 // been cleared yet. Virtual for testing purposes.
721 virtual bool waiting_for_auth() const;
723 // The set of currently enabled sync experiments.
724 const syncer::Experiments
& current_experiments() const;
726 // OAuth2TokenService::Consumer implementation.
727 void OnGetTokenSuccess(const OAuth2TokenService::Request
* request
,
728 const std::string
& access_token
,
729 const base::Time
& expiration_time
) override
;
730 void OnGetTokenFailure(const OAuth2TokenService::Request
* request
,
731 const GoogleServiceAuthError
& error
) override
;
733 // OAuth2TokenService::Observer implementation.
734 void OnRefreshTokenAvailable(const std::string
& account_id
) override
;
735 void OnRefreshTokenRevoked(const std::string
& account_id
) override
;
736 void OnRefreshTokensLoaded() override
;
738 // KeyedService implementation. This must be called exactly
739 // once (before this object is destroyed).
740 void Shutdown() override
;
742 // Called when a datatype (SyncableService) has a need for sync to start
743 // ASAP, presumably because a local change event has occurred but we're
744 // still in deferred start mode, meaning the SyncableService hasn't been
745 // told to MergeDataAndStartSyncing yet.
746 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
);
748 // Return sync token status.
749 SyncTokenStatus
GetSyncTokenStatus() const;
751 browser_sync::FaviconCache
* GetFaviconCache();
753 // Overrides the NetworkResources used for Sync connections.
754 // This function takes ownership of |network_resources|.
755 void OverrideNetworkResourcesForTest(
756 scoped_ptr
<syncer::NetworkResources
> network_resources
);
758 virtual bool IsDataTypeControllerRunning(syncer::ModelType type
) const;
760 // Returns true if the SyncBackendHost has told us it's ready to accept
761 // changes. This should only be used for sync's internal configuration logic
762 // (such as deciding when to prompt for an encryption passphrase).
763 virtual bool backend_initialized() const;
765 // Returns the current mode the backend is in.
766 BackendMode
backend_mode() const;
768 // Whether the data types active for the current mode have finished
770 bool ConfigurationDone() const;
772 // Helpers for testing rollback.
773 void SetBrowsingDataRemoverObserverForTesting(
774 BrowsingDataRemover::Observer
* observer
);
775 void SetClearingBrowseringDataForTesting(base::Callback
<
776 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
779 // Return the base URL of the Sync Server.
780 static GURL
GetSyncServiceURL(const base::CommandLine
& command_line
);
782 base::Time
GetDeviceBackupTimeForTesting() const;
784 // This triggers a Directory::SaveChanges() call on the sync thread.
785 // It should be used to persist data to disk when the process might be
786 // killed in the near future.
787 void FlushDirectory() const;
789 // Needed to test whether the directory is deleted properly.
790 base::FilePath
GetDirectoryPathForTest() const;
792 // Sometimes we need to wait for tasks on the sync thread in tests.
793 base::MessageLoop
* GetSyncLoopForTest() const;
796 // Helper to configure the priority data types.
797 void ConfigurePriorityDataTypes();
799 // Helper to install and configure a data type manager.
800 void ConfigureDataTypeManager();
802 // Shuts down the backend sync components.
803 // |reason| dictates if syncing is being disabled or not, and whether
804 // to claim ownership of sync thread from backend.
805 void ShutdownImpl(syncer::ShutdownReason reason
);
807 // Return SyncCredentials from the OAuth2TokenService.
808 syncer::SyncCredentials
GetCredentials();
810 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
812 const sync_driver::DataTypeController::TypeMap
&
813 directory_data_type_controllers() {
814 return directory_data_type_controllers_
;
817 // Helper method for managing encryption UI.
818 bool IsEncryptedDatatypeEnabled() const;
820 // Helper for OnUnrecoverableError.
821 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
822 // and in SyncBackendHost::Shutdown.
823 void OnUnrecoverableErrorImpl(
824 const tracked_objects::Location
& from_here
,
825 const std::string
& message
,
826 bool delete_sync_database
);
828 virtual bool NeedBackup() const;
830 // This is a cache of the last authentication response we received from the
831 // sync server. The UI queries this to display appropriate messaging to the
833 GoogleServiceAuthError last_auth_error_
;
835 // Our asynchronous backend to communicate with sync components living on
837 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
839 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
840 // was required for encryption, decryption with a cached passphrase, or
841 // because a new passphrase is required?
842 syncer::PassphraseRequiredReason passphrase_required_reason_
;
845 enum UnrecoverableErrorReason
{
848 ERROR_REASON_BACKEND_INIT_FAILURE
,
849 ERROR_REASON_CONFIGURATION_RETRY
,
850 ERROR_REASON_CONFIGURATION_FAILURE
,
851 ERROR_REASON_ACTIONABLE_ERROR
,
855 enum AuthErrorMetric
{
856 AUTH_ERROR_ENCOUNTERED
,
861 friend class ProfileSyncServicePasswordTest
;
862 friend class SyncTest
;
863 friend class TestProfileSyncService
;
864 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
866 // Update the last auth error and notify observers of error state.
867 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
869 // Detects and attempts to recover from a previous improper datatype
870 // configuration where Keep Everything Synced and the preferred types were
871 // not correctly set.
872 void TrySyncDatatypePrefRecovery();
874 // Puts the backend's sync scheduler into NORMAL mode.
875 // Called when configuration is complete.
876 void StartSyncingWithServer();
878 // Called when we've determined that we don't need a passphrase (either
879 // because OnPassphraseAccepted() was called, or because we've gotten a
880 // OnPassphraseRequired() but no data types are enabled).
881 void ResolvePassphraseRequired();
883 // During initial signin, ProfileSyncService caches the user's signin
884 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
885 // This routine is invoked once the backend has started up to use the
886 // cached passphrase and clear it out when it is done.
887 void ConsumeCachedPassphraseIfPossible();
889 // RequestAccessToken initiates RPC to request downscoped access token from
890 // refresh token. This happens when a new OAuth2 login token is loaded and
891 // when sync server returns AUTH_ERROR which indicates it is time to refresh
893 virtual void RequestAccessToken();
895 // Return true if backend should start from a fresh sync DB.
896 bool ShouldDeleteSyncFolder();
898 // If |delete_sync_data_folder| is true, then this method will delete all
899 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
900 void InitializeBackend(bool delete_sync_data_folder
);
902 // Initializes the various settings from the command line.
905 // Sets the last synced time to the current time.
906 void UpdateLastSyncedTime();
908 void NotifyObservers();
909 void NotifySyncCycleCompleted();
911 void ClearStaleErrors();
913 void ClearUnrecoverableError();
915 // Starts up the backend sync components. |mode| specifies the kind of
916 // backend to start, one of SYNC, BACKUP or ROLLBACK.
917 virtual void StartUpSlowBackendComponents(BackendMode mode
);
919 // Collects preferred sync data types from |preference_providers_|.
920 syncer::ModelTypeSet
GetDataTypesFromPreferenceProviders() const;
922 // Called when the user changes the sync configuration, to update the UMA
924 void UpdateSelectedTypesHistogram(
925 bool sync_everything
,
926 const syncer::ModelTypeSet chosen_types
) const;
928 #if defined(OS_CHROMEOS)
929 // Refresh spare sync bootstrap token for re-enabling the sync service.
930 // Called on successful sign-in notifications.
931 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
934 // Internal unrecoverable error handler. Used to track error reason via
935 // Sync.UnrecoverableErrors histogram.
936 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
937 const std::string
& message
,
938 bool delete_sync_database
,
939 UnrecoverableErrorReason reason
);
941 // Returns the type of manager to use according to |backend_mode_|.
942 syncer::SyncManagerFactory::MANAGER_TYPE
GetManagerType() const;
944 // Update UMA for syncing backend.
945 void UpdateBackendInitUMA(bool success
);
947 // Various setup following backend initialization, mostly for syncing backend.
948 void PostBackendInitialization();
950 // True if a syncing backend exists.
951 bool HasSyncingBackend() const;
953 // Update first sync time stored in preferences
954 void UpdateFirstSyncTimePref();
956 // Clear browsing data since first sync during rollback.
957 void ClearBrowsingDataSinceFirstSync();
959 // Post background task to check sync backup DB state if needed.
960 void CheckSyncBackupIfNeeded();
962 // Callback to receive backup DB check result.
963 void CheckSyncBackupCallback(base::Time backup_time
);
965 // Callback function to call |startup_controller_|.TryStart() after
966 // backup/rollback finishes;
967 void TryStartSyncAfterBackup();
969 // Clean up prefs and backup DB when rollback is not needed.
970 void CleanUpBackup();
972 // Tell the sync server that this client has disabled sync.
973 void RemoveClientFromServer() const;
975 // Factory used to create various dependent objects.
976 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
978 // The profile whose data we are synchronizing.
981 // The class that handles getting, setting, and persisting sync
983 sync_driver::SyncPrefs sync_prefs_
;
985 // TODO(ncarter): Put this in a profile, once there is UI for it.
986 // This specifies where to find the sync server.
987 const GURL sync_service_url_
;
989 // The time that OnConfigureStart is called. This member is zero if
990 // OnConfigureStart has not yet been called, and is reset to zero once
991 // OnConfigureDone is called.
992 base::Time sync_configure_start_time_
;
994 // Indicates if this is the first time sync is being configured. This value
995 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
996 bool is_first_time_sync_configure_
;
998 // List of available data type controllers for directory types.
999 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_
;
1001 // Whether the SyncBackendHost has been initialized.
1002 bool backend_initialized_
;
1004 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1005 // ProfileSyncService from starting backend till browser restarted or user
1007 bool sync_disabled_by_admin_
;
1009 // Set to true if a signin has completed but we're still waiting for the
1010 // backend to refresh its credentials.
1011 bool is_auth_in_progress_
;
1013 // Encapsulates user signin - used to set/get the user's authenticated
1015 const scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_
;
1017 // Information describing an unrecoverable error.
1018 UnrecoverableErrorReason unrecoverable_error_reason_
;
1019 std::string unrecoverable_error_message_
;
1020 tracked_objects::Location unrecoverable_error_location_
;
1022 // Manages the start and stop of the directory data types.
1023 scoped_ptr
<sync_driver::DataTypeManager
> directory_data_type_manager_
;
1025 // Manager for the non-blocking data types.
1026 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_
;
1028 ObserverList
<ProfileSyncServiceBase::Observer
> observers_
;
1029 ObserverList
<browser_sync::ProtocolEventObserver
> protocol_event_observers_
;
1030 ObserverList
<syncer::TypeDebugInfoObserver
> type_debug_info_observers_
;
1032 std::set
<SyncTypePreferenceProvider
*> preference_providers_
;
1034 syncer::SyncJsController sync_js_controller_
;
1036 // This allows us to gracefully handle an ABORTED return code from the
1037 // DataTypeManager in the event that the server informed us to cease and
1038 // desist syncing immediately.
1039 bool expect_sync_configuration_aborted_
;
1041 // Sometimes we need to temporarily hold on to a passphrase because we don't
1042 // yet have a backend to send it to. This happens during initialization as
1043 // we don't StartUp until we have a valid token, which happens after valid
1044 // credentials were provided.
1045 std::string cached_passphrase_
;
1047 // The current set of encrypted types. Always a superset of
1048 // syncer::Cryptographer::SensitiveTypes().
1049 syncer::ModelTypeSet encrypted_types_
;
1051 // Whether encrypting everything is allowed.
1052 bool encrypt_everything_allowed_
;
1054 // Whether we want to encrypt everything.
1055 bool encrypt_everything_
;
1057 // Whether we're waiting for an attempt to encryption all sync data to
1058 // complete. We track this at this layer in order to allow the user to cancel
1059 // if they e.g. don't remember their explicit passphrase.
1060 bool encryption_pending_
;
1062 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
1064 // This is the last |SyncProtocolError| we received from the server that had
1065 // an action set on it.
1066 syncer::SyncProtocolError last_actionable_error_
;
1068 // Exposes sync errors to the UI.
1069 scoped_ptr
<SyncErrorController
> sync_error_controller_
;
1071 // Tracks the set of failed data types (those that encounter an error
1072 // or must delay loading for some reason).
1073 sync_driver::DataTypeStatusTable data_type_status_table_
;
1075 sync_driver::DataTypeManager::ConfigureStatus configure_status_
;
1077 // The set of currently enabled sync experiments.
1078 syncer::Experiments current_experiments_
;
1080 // Sync's internal debug info listener. Used to record datatype configuration
1081 // and association information.
1082 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
1084 // A thread where all the sync operations happen.
1086 // * Created when backend starts for the first time.
1087 // * If sync is disabled, PSS claims ownership from backend.
1088 // * If sync is reenabled, PSS passes ownership to new backend.
1089 scoped_ptr
<base::Thread
> sync_thread_
;
1091 // ProfileSyncService uses this service to get access tokens.
1092 ProfileOAuth2TokenService
* const oauth2_token_service_
;
1094 // ProfileSyncService needs to remember access token in order to invalidate it
1095 // with OAuth2TokenService.
1096 std::string access_token_
;
1098 // ProfileSyncService needs to hold reference to access_token_request_ for
1099 // the duration of request in order to receive callbacks.
1100 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
1102 // If RequestAccessToken fails with transient error then retry requesting
1103 // access token with exponential backoff.
1104 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
1105 net::BackoffEntry request_access_token_backoff_
;
1107 // States related to sync token and connection.
1108 base::Time connection_status_update_time_
;
1109 syncer::ConnectionStatus connection_status_
;
1110 base::Time token_request_time_
;
1111 base::Time token_receive_time_
;
1112 GoogleServiceAuthError last_get_token_error_
;
1113 base::Time next_token_request_time_
;
1115 scoped_ptr
<sync_driver::LocalDeviceInfoProvider
> local_device_
;
1117 // Locally owned SyncableService implementations.
1118 scoped_ptr
<browser_sync::SessionsSyncManager
> sessions_sync_manager_
;
1119 scoped_ptr
<sync_driver::DeviceInfoSyncService
> device_info_sync_service_
;
1121 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
1123 scoped_ptr
<browser_sync::StartupController
> startup_controller_
;
1125 scoped_ptr
<browser_sync::BackupRollbackController
>
1126 backup_rollback_controller_
;
1128 // Mode of current backend.
1129 BackendMode backend_mode_
;
1131 // Whether backup is needed before sync starts.
1134 // Whether backup is finished.
1135 bool backup_finished_
;
1137 base::Time backup_start_time_
;
1140 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
1141 clear_browsing_data_
;
1143 // Last time when pre-sync data was saved. NULL pointer means backup data
1144 // state is unknown. If time value is null, backup data doesn't exist.
1145 scoped_ptr
<base::Time
> last_backup_time_
;
1147 BrowsingDataRemover::Observer
* browsing_data_remover_observer_
;
1149 // The full path to the sync data directory.
1150 base::FilePath directory_path_
;
1152 scoped_ptr
<browser_sync::SyncStoppedReporter
> sync_stopped_reporter_
;
1154 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
1156 // We don't use |weak_factory_| for the StartupController because the weak
1157 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1158 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1159 // StartupController an Unretained reference to future-proof against
1160 // the controller impl changing to post tasks. Therefore, we have a separate
1162 base::WeakPtrFactory
<ProfileSyncService
> startup_controller_weak_factory_
;
1164 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1167 bool ShouldShowActionOnUI(
1168 const syncer::SyncProtocolError
& error
);
1171 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_