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/memory_pressure_listener.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/scoped_vector.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/observer_list.h"
22 #include "base/strings/string16.h"
23 #include "base/time/time.h"
24 #include "base/timer/timer.h"
25 #include "chrome/browser/browsing_data/browsing_data_remover.h"
26 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
27 #include "chrome/browser/sync/backup_rollback_controller.h"
28 #include "chrome/browser/sync/glue/sync_backend_host.h"
29 #include "chrome/browser/sync/protocol_event_observer.h"
30 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
31 #include "chrome/browser/sync/startup_controller.h"
32 #include "chrome/browser/sync/sync_stopped_reporter.h"
33 #include "components/keyed_service/core/keyed_service.h"
34 #include "components/signin/core/browser/signin_manager_base.h"
35 #include "components/sync_driver/data_type_controller.h"
36 #include "components/sync_driver/data_type_manager.h"
37 #include "components/sync_driver/data_type_manager_observer.h"
38 #include "components/sync_driver/data_type_status_table.h"
39 #include "components/sync_driver/device_info_sync_service.h"
40 #include "components/sync_driver/local_device_info_provider.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 "components/sync_driver/sync_service.h"
45 #include "google_apis/gaia/google_service_auth_error.h"
46 #include "google_apis/gaia/oauth2_token_service.h"
47 #include "net/base/backoff_entry.h"
48 #include "sync/internal_api/public/base/model_type.h"
49 #include "sync/internal_api/public/engine/model_safe_worker.h"
50 #include "sync/internal_api/public/shutdown_reason.h"
51 #include "sync/internal_api/public/sync_manager_factory.h"
52 #include "sync/internal_api/public/util/experiments.h"
53 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
54 #include "sync/js/sync_js_controller.h"
58 class ProfileOAuth2TokenService
;
59 class ProfileSyncComponentsFactory
;
60 class SupervisedUserSigninManagerWrapper
;
61 class SyncErrorController
;
62 class SyncTypePreferenceProvider
;
68 namespace browser_sync
{
69 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 class DeviceInfoSyncService
;
83 class LocalDeviceInfoProvider
;
84 } // namespace sync_driver
87 class BaseTransaction
;
88 class NetworkResources
;
89 struct CommitCounters
;
90 struct StatusCounters
;
91 struct SyncCredentials
;
92 struct UpdateCounters
;
98 } // namespace sync_pb
100 // ProfileSyncService is the layer between browser subsystems like bookmarks,
101 // and the sync backend. Each subsystem is logically thought of as being
104 // Individual datatypes can, at any point, be in a variety of stages of being
105 // "enabled". Here are some specific terms for concepts used in this class:
107 // 'Registered' (feature suppression for a datatype)
109 // When a datatype is registered, the user has the option of syncing it.
110 // The sync opt-in UI will show only registered types; a checkbox should
111 // never be shown for an unregistered type, and nor should it ever be
114 // A datatype is considered registered once RegisterDataTypeController
115 // has been called with that datatype's DataTypeController.
117 // 'Preferred' (user preferences and opt-out for a datatype)
119 // This means the user's opt-in or opt-out preference on a per-datatype
120 // basis. The sync service will try to make active exactly these types.
121 // If a user has opted out of syncing a particular datatype, it will
122 // be registered, but not preferred.
124 // This state is controlled by the ConfigurePreferredDataTypes and
125 // GetPreferredDataTypes. They are stored in the preferences system,
126 // and persist; though if a datatype is not registered, it cannot
127 // be a preferred datatype.
129 // 'Active' (run-time initialization of sync system for a datatype)
131 // An active datatype is a preferred datatype that is actively being
132 // synchronized: the syncer has been instructed to querying the server
133 // for this datatype, first-time merges have finished, and there is an
134 // actively installed ChangeProcessor that listens for changes to this
135 // datatype, propagating such changes into and out of the sync backend
138 // When a datatype is in the process of becoming active, it may be
139 // in some intermediate state. Those finer-grained intermediate states
140 // are differentiated by the DataTypeController state.
142 // Sync Configuration:
144 // Sync configuration is accomplished via the following APIs:
145 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
146 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
147 // using the passed passphrase.
148 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
151 // Additionally, the current sync configuration can be fetched by calling
152 // * GetRegisteredDataTypes()
153 // * GetPreferredDataTypes()
154 // * GetActiveDataTypes()
155 // * IsUsingSecondaryPassphrase()
156 // * EncryptEverythingEnabled()
157 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
159 // The "sync everything" state cannot be read from ProfileSyncService, but
160 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
162 // Initial sync setup:
164 // For privacy reasons, it is usually desirable to avoid syncing any data
165 // types until the user has finished setting up sync. There are two APIs
166 // that control the initial sync download:
168 // * SetSyncSetupCompleted()
169 // * SetSetupInProgress()
171 // SetSyncSetupCompleted() should be called once the user has finished setting
172 // up sync at least once on their account. SetSetupInProgress(true) should be
173 // called while the user is actively configuring their account, and then
174 // SetSetupInProgress(false) should be called when configuration is complete.
175 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
176 // been called, then the sync engine knows not to download any user data.
178 // When initial sync is complete, the UI code should call
179 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
180 // tell the sync engine that setup is completed and it can begin downloading
181 // data from the sync server.
183 class ProfileSyncService
: public sync_driver::SyncService
,
184 public sync_driver::SyncFrontend
,
185 public sync_driver::SyncPrefObserver
,
186 public sync_driver::DataTypeManagerObserver
,
187 public syncer::UnrecoverableErrorHandler
,
189 public OAuth2TokenService::Consumer
,
190 public OAuth2TokenService::Observer
,
191 public SigninManagerBase::Observer
{
193 typedef browser_sync::SyncBackendHost::Status Status
;
195 // Status of sync server connection, sync token and token request.
196 struct SyncTokenStatus
{
200 // Sync server connection status reported by sync backend.
201 base::Time connection_status_update_time
;
202 syncer::ConnectionStatus connection_status
;
204 // Times when OAuth2 access token is requested and received.
205 base::Time token_request_time
;
206 base::Time token_receive_time
;
208 // Error returned by OAuth2TokenService for token request and time when
209 // next request is scheduled.
210 GoogleServiceAuthError last_get_token_error
;
211 base::Time next_token_request_time
;
214 enum SyncEventCodes
{
215 MIN_SYNC_EVENT_CODE
= 0,
217 // Events starting the sync service.
218 START_FROM_NTP
= 1, // Sync was started from the ad in NTP
219 START_FROM_WRENCH
= 2, // Sync was started from the Wrench menu.
220 START_FROM_OPTIONS
= 3, // Sync was started from Wrench->Options.
221 START_FROM_BOOKMARK_MANAGER
= 4, // Sync was started from Bookmark manager.
222 START_FROM_PROFILE_MENU
= 5, // Sync was started from multiprofile menu.
223 START_FROM_URL
= 6, // Sync was started from a typed URL.
225 // Events regarding cancellation of the signon process of sync.
226 CANCEL_FROM_SIGNON_WITHOUT_AUTH
= 10, // Cancelled before submitting
227 // username and password.
228 CANCEL_DURING_SIGNON
= 11, // Cancelled after auth.
229 CANCEL_DURING_CONFIGURE
= 12, // Cancelled before choosing data
230 // types and clicking OK.
231 // Events resulting in the stoppage of sync service.
232 STOP_FROM_OPTIONS
= 20, // Sync was stopped from Wrench->Options.
233 STOP_FROM_ADVANCED_DIALOG
= 21, // Sync was stopped via advanced settings.
235 // Miscellaneous events caused by sync service.
240 enum SyncStatusSummary
{
244 DATATYPES_NOT_INITIALIZED
,
253 SYNC
, // Backend for syncing.
254 BACKUP
, // Backend for backup.
255 ROLLBACK
// Backend for rollback.
258 // Default sync server URL.
259 static const char* kSyncServerUrl
;
260 // Sync server URL for dev channel users
261 static const char* kDevServerUrl
;
263 // Takes ownership of |factory| and |signin_wrapper|.
265 scoped_ptr
<ProfileSyncComponentsFactory
> factory
,
267 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
268 ProfileOAuth2TokenService
* oauth2_token_service
,
269 browser_sync::ProfileSyncServiceStartBehavior start_behavior
);
270 ~ProfileSyncService() override
;
272 // Initializes the object. This must be called at most once, and
273 // immediately after an object of this class is constructed.
276 // sync_driver::SyncService implementation
277 bool HasSyncSetupCompleted() const override
;
278 bool IsSyncAllowed() const override
;
279 bool IsSyncActive() const override
;
280 bool IsSyncEnabledAndLoggedIn() override
;
281 void DisableForUser() override
;
282 void RequestStop() override
;
283 void RequestStart() override
;
284 syncer::ModelTypeSet
GetActiveDataTypes() const override
;
285 syncer::ModelTypeSet
GetPreferredDataTypes() const override
;
286 void OnUserChoseDatatypes(bool sync_everything
,
287 syncer::ModelTypeSet chosen_types
) override
;
288 void SetSyncSetupCompleted() override
;
289 bool FirstSetupInProgress() const override
;
290 void SetSetupInProgress(bool setup_in_progress
) override
;
291 bool setup_in_progress() const override
;
292 bool ConfigurationDone() const override
;
293 const GoogleServiceAuthError
& GetAuthError() const override
;
294 bool HasUnrecoverableError() const override
;
295 bool backend_initialized() const override
;
296 bool IsPassphraseRequiredForDecryption() const override
;
297 base::Time
GetExplicitPassphraseTime() const override
;
298 bool IsUsingSecondaryPassphrase() const override
;
299 void EnableEncryptEverything() override
;
300 void SetEncryptionPassphrase(const std::string
& passphrase
,
301 PassphraseType type
) override
;
302 bool SetDecryptionPassphrase(const std::string
& passphrase
) override
304 void AddObserver(sync_driver::SyncServiceObserver
* observer
) override
;
305 void RemoveObserver(sync_driver::SyncServiceObserver
* observer
) override
;
307 const sync_driver::SyncServiceObserver
* observer
) const override
;
309 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver
* observer
);
310 void RemoveProtocolEventObserver(
311 browser_sync::ProtocolEventObserver
* observer
);
313 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
314 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
316 // Add a sync type preference provider. Each provider may only be added once.
317 void AddPreferenceProvider(SyncTypePreferenceProvider
* provider
);
318 // Remove a sync type preference provider. May only be called for providers
319 // that have been added. Providers must not remove themselves while being
321 void RemovePreferenceProvider(SyncTypePreferenceProvider
* provider
);
322 // Check whether a given sync type preference provider has been added.
323 bool HasPreferenceProvider(SyncTypePreferenceProvider
* provider
) const;
325 // Asynchronously fetches base::Value representations of all sync nodes and
326 // returns them to the specified callback on this thread.
328 // These requests can live a long time and return when you least expect it.
329 // For safety, the callback should be bound to some sort of WeakPtr<> or
332 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
334 void RegisterAuthNotifications();
335 void UnregisterAuthNotifications();
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 the SyncableService for syncer::DEVICE_INFO.
378 virtual syncer::SyncableService
* GetDeviceInfoSyncableService();
380 // Returns DeviceInfo provider for the local device.
381 virtual sync_driver::LocalDeviceInfoProvider
* GetLocalDeviceInfoProvider();
383 // Returns synced devices tracker.
384 virtual sync_driver::DeviceInfoTracker
* GetDeviceInfoTracker() const;
386 // Fills state_map with a map of current data types that are possible to
387 // sync, as well as their states.
388 void GetDataTypeControllerStates(
389 sync_driver::DataTypeController::StateMap
* state_map
) const;
391 // Disables sync for the user and prevents it from starting on next restart.
392 virtual void StopSyncingPermanently();
394 // SyncFrontend implementation.
395 void OnBackendInitialized(
396 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
397 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
399 const std::string
& cache_guid
,
400 bool success
) override
;
401 void OnSyncCycleCompleted() override
;
402 void OnProtocolEvent(const syncer::ProtocolEvent
& event
) override
;
403 void OnDirectoryTypeCommitCounterUpdated(
404 syncer::ModelType type
,
405 const syncer::CommitCounters
& counters
) override
;
406 void OnDirectoryTypeUpdateCounterUpdated(
407 syncer::ModelType type
,
408 const syncer::UpdateCounters
& counters
) override
;
409 void OnDirectoryTypeStatusCounterUpdated(
410 syncer::ModelType type
,
411 const syncer::StatusCounters
& counters
) override
;
412 void OnConnectionStatusChange(syncer::ConnectionStatus status
) override
;
413 void OnPassphraseRequired(
414 syncer::PassphraseRequiredReason reason
,
415 const sync_pb::EncryptedData
& pending_keys
) override
;
416 void OnPassphraseAccepted() override
;
417 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types
,
418 bool encrypt_everything
) override
;
419 void OnEncryptionComplete() override
;
420 void OnMigrationNeededForTypes(syncer::ModelTypeSet types
) override
;
421 void OnExperimentsChanged(const syncer::Experiments
& experiments
) override
;
422 void OnActionableError(const syncer::SyncProtocolError
& error
) override
;
424 // DataTypeManagerObserver implementation.
425 void OnConfigureDone(
426 const sync_driver::DataTypeManager::ConfigureResult
& result
) override
;
427 void OnConfigureStart() override
;
429 // DataTypeEncryptionHandler implementation.
430 bool IsPassphraseRequired() const override
;
431 syncer::ModelTypeSet
GetEncryptedDataTypes() const override
;
433 // SigninManagerBase::Observer implementation.
434 void GoogleSigninSucceeded(const std::string
& account_id
,
435 const std::string
& username
,
436 const std::string
& password
) override
;
437 void GoogleSignedOut(const std::string
& account_id
,
438 const std::string
& username
) override
;
440 // Get the sync status code.
441 SyncStatusSummary
QuerySyncStatusSummary();
443 // Get a description of the sync status for displaying in the user interface.
444 std::string
QuerySyncStatusSummaryString();
446 // Initializes a struct of status indicators with data from the backend.
447 // Returns false if the backend was not available for querying; in that case
448 // the struct will be filled with default data.
449 virtual bool QueryDetailedSyncStatus(
450 browser_sync::SyncBackendHost::Status
* result
);
452 // Reconfigures the data type manager with the latest enabled types.
453 // Note: Does not initialize the backend if it is not already initialized.
454 // This function needs to be called only after sync has been initialized
455 // (i.e.,only for reconfigurations). The reason we don't initialize the
456 // backend is because if we had encountered an unrecoverable error we don't
457 // want to startup once more.
458 // This function is called by |SetSetupInProgress|.
459 virtual void ReconfigureDatatypeManager();
461 const std::string
& unrecoverable_error_message() {
462 return unrecoverable_error_message_
;
464 tracked_objects::Location
unrecoverable_error_location() {
465 return unrecoverable_error_location_
;
468 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
469 return passphrase_required_reason_
;
472 // Returns a user-friendly string form of last synced time (in minutes).
473 virtual base::string16
GetLastSyncedTimeString() const;
475 // Returns a human readable string describing backend initialization state.
476 std::string
GetBackendInitializationStateString() const;
478 // Returns true if sync is requested to be running by the user.
479 // Note that this does not mean that sync WILL be running; e.g. if
480 // IsSyncAllowed() is false then sync won't start, and if the user
481 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
482 // never become active. Use IsSyncActive to see if sync is running.
483 virtual bool IsSyncRequested() const;
485 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
487 // The profile we are syncing for.
488 Profile
* profile() const { return profile_
; }
490 // Returns a weak pointer to the service's JsController.
491 // Overrideable for testing purposes.
492 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
494 // Record stats on various events.
495 static void SyncEvent(SyncEventCodes code
);
497 // Returns whether sync is allowed to run based on command-line switches.
498 // Profile::IsSyncAllowed() is probably a better signal than this function.
499 // This function can be called from any thread, and the implementation doesn't
500 // assume it's running on the UI thread.
501 static bool IsSyncAllowedByFlag();
503 // Returns whether sync is managed, i.e. controlled by configuration
504 // management. If so, the user is not allowed to configure sync.
505 virtual bool IsManaged() const;
507 // syncer::UnrecoverableErrorHandler implementation.
508 void OnUnrecoverableError(const tracked_objects::Location
& from_here
,
509 const std::string
& message
) override
;
511 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
512 // not change the preferred state of a datatype, and is not persisted across
514 void ReenableDatatype(syncer::ModelType type
);
516 // The functions below (until ActivateDataType()) should only be
517 // called if backend_initialized() is true.
519 // TODO(akalin): This is called mostly by ModelAssociators and
520 // tests. Figure out how to pass the handle to the ModelAssociators
521 // directly, figure out how to expose this to tests, and remove this
523 virtual syncer::UserShare
* GetUserShare() const;
525 // TODO(akalin): These two functions are used only by
526 // ProfileSyncServiceHarness. Figure out a different way to expose
527 // this info to that class, and remove these functions.
529 virtual syncer::sessions::SyncSessionSnapshot
530 GetLastSessionSnapshot() const;
532 // Returns whether or not the underlying sync engine has made any
533 // local changes to items that have not yet been synced with the
535 bool HasUnsyncedItems() const;
537 // Used by ProfileSyncServiceHarness. May return NULL.
538 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
540 // Used by tests to inspect interaction with OAuth2TokenService.
541 bool IsRetryingAccessTokenFetchForTest() const;
543 // Used by tests to inspect the OAuth2 access tokens used by PSS.
544 std::string
GetAccessTokenForTest() const;
546 // TODO(sync): This is only used in tests. Can we remove it?
547 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
549 // Returns a ListValue indicating the status of all registered types.
552 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
553 // where <name> is a type's name, <value> is a string providing details for
554 // the type's status, and <status> is one of "error", "warning" or "ok"
555 // depending on the type's current status.
557 // This function is used by about_sync_util.cc to help populate the about:sync
558 // page. It returns a ListValue rather than a DictionaryValue in part to make
559 // it easier to iterate over its elements when constructing that page.
560 base::Value
* GetTypeStatusMap() const;
562 // Overridden by tests.
563 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
564 virtual void DeactivateDataType(syncer::ModelType type
);
566 // SyncPrefObserver implementation.
567 void OnSyncManagedPrefChange(bool is_sync_managed
) override
;
569 // Changes which data types we're going to be syncing to |preferred_types|.
570 // If it is running, the DataTypeManager will be instructed to reconfigure
571 // the sync backend so that exactly these datatypes are actively synced. See
572 // class comment for more on what it means for a datatype to be Preferred.
573 virtual void ChangePreferredDataTypes(
574 syncer::ModelTypeSet preferred_types
);
576 // Returns the set of directory types which are preferred for enabling.
577 virtual syncer::ModelTypeSet
GetPreferredDirectoryDataTypes() const;
579 // Returns the set of off-thread types which are preferred for enabling.
580 virtual syncer::ModelTypeSet
GetPreferredNonBlockingDataTypes() const;
582 // Returns the set of types which are enforced programmatically and can not
583 // be disabled by the user.
584 virtual syncer::ModelTypeSet
GetForcedDataTypes() const;
586 // Gets the set of all data types that could be allowed (the set that
587 // should be advertised to the user). These will typically only change
588 // via a command-line option. See class comment for more on what it means
589 // for a datatype to be Registered.
590 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
592 // Gets the set of directory types which could be allowed.
593 virtual syncer::ModelTypeSet
GetRegisteredDirectoryDataTypes() const;
595 // Gets the set of off-thread types which could be allowed.
596 virtual syncer::ModelTypeSet
GetRegisteredNonBlockingDataTypes() const;
598 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
599 // for sensitive data types. Caller must be holding a
600 // syncapi::BaseTransaction to ensure thread safety.
601 virtual bool IsCryptographerReady(
602 const syncer::BaseTransaction
* trans
) const;
604 // Returns the actual passphrase type being used for encryption.
605 virtual syncer::PassphraseType
GetPassphraseType() const;
607 // Note about setting passphrases: There are different scenarios under which
608 // we might want to apply a passphrase. It could be for first-time encryption,
609 // re-encryption, or for decryption by clients that sign in at a later time.
610 // In addition, encryption can either be done using a custom passphrase, or by
611 // reusing the GAIA password. Depending on what is happening in the system,
612 // callers should determine which of the two methods below must be used.
614 // Returns true if encrypting all the sync data is allowed. If this method
615 // returns false, EnableEncryptEverything() should not be called.
616 virtual bool EncryptEverythingAllowed() const;
618 // Sets whether encrypting all the sync data is allowed or not.
619 virtual void SetEncryptEverythingAllowed(bool allowed
);
621 // Returns true if we are currently set to encrypt all the sync data. Note:
622 // this is based on the cryptographer's settings, so if the user has recently
623 // requested encryption to be turned on, this may not be true yet. For that,
624 // encryption_pending() must be checked.
625 virtual bool EncryptEverythingEnabled() const;
627 // Returns true if the syncer is waiting for new datatypes to be encrypted.
628 virtual bool encryption_pending() const;
630 const GURL
& sync_service_url() const { return sync_service_url_
; }
631 SigninManagerBase
* signin() const;
634 bool auto_start_enabled() const;
636 SyncErrorController
* sync_error_controller() {
637 return sync_error_controller_
.get();
640 // TODO(sync): This is only used in tests. Can we remove it?
641 const sync_driver::DataTypeStatusTable
& data_type_status_table() const;
643 sync_driver::DataTypeManager::ConfigureStatus
configure_status() {
644 return configure_status_
;
647 // If true, the ProfileSyncService has detected that a new GAIA signin has
648 // succeeded, and is waiting for initialization to complete. This is used by
649 // the UI to differentiate between a new auth error (encountered as part of
650 // the initialization process) and a pre-existing auth error that just hasn't
651 // been cleared yet. Virtual for testing purposes.
652 virtual bool waiting_for_auth() const;
654 // The set of currently enabled sync experiments.
655 const syncer::Experiments
& current_experiments() const;
657 // OAuth2TokenService::Consumer implementation.
658 void OnGetTokenSuccess(const OAuth2TokenService::Request
* request
,
659 const std::string
& access_token
,
660 const base::Time
& expiration_time
) override
;
661 void OnGetTokenFailure(const OAuth2TokenService::Request
* request
,
662 const GoogleServiceAuthError
& error
) override
;
664 // OAuth2TokenService::Observer implementation.
665 void OnRefreshTokenAvailable(const std::string
& account_id
) override
;
666 void OnRefreshTokenRevoked(const std::string
& account_id
) override
;
667 void OnRefreshTokensLoaded() override
;
669 // KeyedService implementation. This must be called exactly
670 // once (before this object is destroyed).
671 void Shutdown() override
;
673 // Called when a datatype (SyncableService) has a need for sync to start
674 // ASAP, presumably because a local change event has occurred but we're
675 // still in deferred start mode, meaning the SyncableService hasn't been
676 // told to MergeDataAndStartSyncing yet.
677 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
);
679 // Return sync token status.
680 SyncTokenStatus
GetSyncTokenStatus() const;
682 browser_sync::FaviconCache
* GetFaviconCache();
684 // Overrides the NetworkResources used for Sync connections.
685 // This function takes ownership of |network_resources|.
686 void OverrideNetworkResourcesForTest(
687 scoped_ptr
<syncer::NetworkResources
> network_resources
);
689 virtual bool IsDataTypeControllerRunning(syncer::ModelType type
) const;
691 // Returns the current mode the backend is in.
692 BackendMode
backend_mode() const;
694 // Helpers for testing rollback.
695 void SetBrowsingDataRemoverObserverForTesting(
696 BrowsingDataRemover::Observer
* observer
);
697 void SetClearingBrowseringDataForTesting(base::Callback
<
698 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
701 // Return the base URL of the Sync Server.
702 static GURL
GetSyncServiceURL(const base::CommandLine
& command_line
);
704 base::Time
GetDeviceBackupTimeForTesting() const;
706 // This triggers a Directory::SaveChanges() call on the sync thread.
707 // It should be used to persist data to disk when the process might be
708 // killed in the near future.
709 void FlushDirectory() const;
711 // Needed to test whether the directory is deleted properly.
712 base::FilePath
GetDirectoryPathForTest() const;
714 // Sometimes we need to wait for tasks on the sync thread in tests.
715 base::MessageLoop
* GetSyncLoopForTest() const;
718 // Helper to configure the priority data types.
719 void ConfigurePriorityDataTypes();
721 // Helper to install and configure a data type manager.
722 void ConfigureDataTypeManager();
724 // Shuts down the backend sync components.
725 // |reason| dictates if syncing is being disabled or not, and whether
726 // to claim ownership of sync thread from backend.
727 void ShutdownImpl(syncer::ShutdownReason reason
);
729 // Return SyncCredentials from the OAuth2TokenService.
730 syncer::SyncCredentials
GetCredentials();
732 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
734 const sync_driver::DataTypeController::TypeMap
&
735 directory_data_type_controllers() {
736 return directory_data_type_controllers_
;
739 // Helper method for managing encryption UI.
740 bool IsEncryptedDatatypeEnabled() const;
742 // Helper for OnUnrecoverableError.
743 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
744 // and in SyncBackendHost::Shutdown.
745 void OnUnrecoverableErrorImpl(
746 const tracked_objects::Location
& from_here
,
747 const std::string
& message
,
748 bool delete_sync_database
);
750 virtual bool NeedBackup() const;
752 // This is a cache of the last authentication response we received from the
753 // sync server. The UI queries this to display appropriate messaging to the
755 GoogleServiceAuthError last_auth_error_
;
757 // Our asynchronous backend to communicate with sync components living on
759 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
761 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
762 // was required for encryption, decryption with a cached passphrase, or
763 // because a new passphrase is required?
764 syncer::PassphraseRequiredReason passphrase_required_reason_
;
767 enum UnrecoverableErrorReason
{
770 ERROR_REASON_BACKEND_INIT_FAILURE
,
771 ERROR_REASON_CONFIGURATION_RETRY
,
772 ERROR_REASON_CONFIGURATION_FAILURE
,
773 ERROR_REASON_ACTIONABLE_ERROR
,
777 enum AuthErrorMetric
{
778 AUTH_ERROR_ENCOUNTERED
,
783 friend class ProfileSyncServicePasswordTest
;
784 friend class SyncTest
;
785 friend class TestProfileSyncService
;
786 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
788 // Update the last auth error and notify observers of error state.
789 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
791 // Detects and attempts to recover from a previous improper datatype
792 // configuration where Keep Everything Synced and the preferred types were
793 // not correctly set.
794 void TrySyncDatatypePrefRecovery();
796 // Puts the backend's sync scheduler into NORMAL mode.
797 // Called when configuration is complete.
798 void StartSyncingWithServer();
800 // Called when we've determined that we don't need a passphrase (either
801 // because OnPassphraseAccepted() was called, or because we've gotten a
802 // OnPassphraseRequired() but no data types are enabled).
803 void ResolvePassphraseRequired();
805 // During initial signin, ProfileSyncService caches the user's signin
806 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
807 // This routine is invoked once the backend has started up to use the
808 // cached passphrase and clear it out when it is done.
809 void ConsumeCachedPassphraseIfPossible();
811 // RequestAccessToken initiates RPC to request downscoped access token from
812 // refresh token. This happens when a new OAuth2 login token is loaded and
813 // when sync server returns AUTH_ERROR which indicates it is time to refresh
815 virtual void RequestAccessToken();
817 // Return true if backend should start from a fresh sync DB.
818 bool ShouldDeleteSyncFolder();
820 // If |delete_sync_data_folder| is true, then this method will delete all
821 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
822 void InitializeBackend(bool delete_sync_data_folder
);
824 // Initializes the various settings from the command line.
827 // Sets the last synced time to the current time.
828 void UpdateLastSyncedTime();
830 void NotifyObservers();
831 void NotifySyncCycleCompleted();
833 void ClearStaleErrors();
835 void ClearUnrecoverableError();
837 // Starts up the backend sync components. |mode| specifies the kind of
838 // backend to start, one of SYNC, BACKUP or ROLLBACK.
839 virtual void StartUpSlowBackendComponents(BackendMode mode
);
841 // Collects preferred sync data types from |preference_providers_|.
842 syncer::ModelTypeSet
GetDataTypesFromPreferenceProviders() const;
844 // Called when the user changes the sync configuration, to update the UMA
846 void UpdateSelectedTypesHistogram(
847 bool sync_everything
,
848 const syncer::ModelTypeSet chosen_types
) const;
850 #if defined(OS_CHROMEOS)
851 // Refresh spare sync bootstrap token for re-enabling the sync service.
852 // Called on successful sign-in notifications.
853 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
856 // Internal unrecoverable error handler. Used to track error reason via
857 // Sync.UnrecoverableErrors histogram.
858 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
859 const std::string
& message
,
860 bool delete_sync_database
,
861 UnrecoverableErrorReason reason
);
863 // Returns the type of manager to use according to |backend_mode_|.
864 syncer::SyncManagerFactory::MANAGER_TYPE
GetManagerType() const;
866 // Update UMA for syncing backend.
867 void UpdateBackendInitUMA(bool success
);
869 // Various setup following backend initialization, mostly for syncing backend.
870 void PostBackendInitialization();
872 // Whether sync has been authenticated with an account ID.
873 bool IsSignedIn() const;
875 // True if a syncing backend exists.
876 bool HasSyncingBackend() const;
878 // Update first sync time stored in preferences
879 void UpdateFirstSyncTimePref();
881 // Clear browsing data since first sync during rollback.
882 void ClearBrowsingDataSinceFirstSync();
884 // Post background task to check sync backup DB state if needed.
885 void CheckSyncBackupIfNeeded();
887 // Callback to receive backup DB check result.
888 void CheckSyncBackupCallback(base::Time backup_time
);
890 // Callback function to call |startup_controller_|.TryStart() after
891 // backup/rollback finishes;
892 void TryStartSyncAfterBackup();
894 // Clean up prefs and backup DB when rollback is not needed.
895 void CleanUpBackup();
897 // Tell the sync server that this client has disabled sync.
898 void RemoveClientFromServer() const;
900 // Called when the system is under memory pressure.
901 void OnMemoryPressure(
902 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
904 // Check if previous shutdown is shutdown cleanly.
905 void ReportPreviousSessionMemoryWarningCount();
907 // Factory used to create various dependent objects.
908 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
910 // The profile whose data we are synchronizing.
913 // The class that handles getting, setting, and persisting sync
915 sync_driver::SyncPrefs sync_prefs_
;
917 // TODO(ncarter): Put this in a profile, once there is UI for it.
918 // This specifies where to find the sync server.
919 const GURL sync_service_url_
;
921 // The time that OnConfigureStart is called. This member is zero if
922 // OnConfigureStart has not yet been called, and is reset to zero once
923 // OnConfigureDone is called.
924 base::Time sync_configure_start_time_
;
926 // Indicates if this is the first time sync is being configured. This value
927 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
928 bool is_first_time_sync_configure_
;
930 // List of available data type controllers for directory types.
931 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_
;
933 // Whether the SyncBackendHost has been initialized.
934 bool backend_initialized_
;
936 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
937 // ProfileSyncService from starting backend till browser restarted or user
939 bool sync_disabled_by_admin_
;
941 // Set to true if a signin has completed but we're still waiting for the
942 // backend to refresh its credentials.
943 bool is_auth_in_progress_
;
945 // Encapsulates user signin - used to set/get the user's authenticated
947 const scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_
;
949 // Information describing an unrecoverable error.
950 UnrecoverableErrorReason unrecoverable_error_reason_
;
951 std::string unrecoverable_error_message_
;
952 tracked_objects::Location unrecoverable_error_location_
;
954 // Manages the start and stop of the directory data types.
955 scoped_ptr
<sync_driver::DataTypeManager
> directory_data_type_manager_
;
957 // Manager for the non-blocking data types.
958 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_
;
960 base::ObserverList
<sync_driver::SyncServiceObserver
> observers_
;
961 base::ObserverList
<browser_sync::ProtocolEventObserver
>
962 protocol_event_observers_
;
963 base::ObserverList
<syncer::TypeDebugInfoObserver
> type_debug_info_observers_
;
965 std::set
<SyncTypePreferenceProvider
*> preference_providers_
;
967 syncer::SyncJsController sync_js_controller_
;
969 // This allows us to gracefully handle an ABORTED return code from the
970 // DataTypeManager in the event that the server informed us to cease and
971 // desist syncing immediately.
972 bool expect_sync_configuration_aborted_
;
974 // Sometimes we need to temporarily hold on to a passphrase because we don't
975 // yet have a backend to send it to. This happens during initialization as
976 // we don't StartUp until we have a valid token, which happens after valid
977 // credentials were provided.
978 std::string cached_passphrase_
;
980 // The current set of encrypted types. Always a superset of
981 // syncer::Cryptographer::SensitiveTypes().
982 syncer::ModelTypeSet encrypted_types_
;
984 // Whether encrypting everything is allowed.
985 bool encrypt_everything_allowed_
;
987 // Whether we want to encrypt everything.
988 bool encrypt_everything_
;
990 // Whether we're waiting for an attempt to encryption all sync data to
991 // complete. We track this at this layer in order to allow the user to cancel
992 // if they e.g. don't remember their explicit passphrase.
993 bool encryption_pending_
;
995 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
997 // This is the last |SyncProtocolError| we received from the server that had
998 // an action set on it.
999 syncer::SyncProtocolError last_actionable_error_
;
1001 // Exposes sync errors to the UI.
1002 scoped_ptr
<SyncErrorController
> sync_error_controller_
;
1004 // Tracks the set of failed data types (those that encounter an error
1005 // or must delay loading for some reason).
1006 sync_driver::DataTypeStatusTable data_type_status_table_
;
1008 sync_driver::DataTypeManager::ConfigureStatus configure_status_
;
1010 // The set of currently enabled sync experiments.
1011 syncer::Experiments current_experiments_
;
1013 // Sync's internal debug info listener. Used to record datatype configuration
1014 // and association information.
1015 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
1017 // A thread where all the sync operations happen.
1019 // * Created when backend starts for the first time.
1020 // * If sync is disabled, PSS claims ownership from backend.
1021 // * If sync is reenabled, PSS passes ownership to new backend.
1022 scoped_ptr
<base::Thread
> sync_thread_
;
1024 // ProfileSyncService uses this service to get access tokens.
1025 ProfileOAuth2TokenService
* const oauth2_token_service_
;
1027 // ProfileSyncService needs to remember access token in order to invalidate it
1028 // with OAuth2TokenService.
1029 std::string access_token_
;
1031 // ProfileSyncService needs to hold reference to access_token_request_ for
1032 // the duration of request in order to receive callbacks.
1033 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
1035 // If RequestAccessToken fails with transient error then retry requesting
1036 // access token with exponential backoff.
1037 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
1038 net::BackoffEntry request_access_token_backoff_
;
1040 // States related to sync token and connection.
1041 base::Time connection_status_update_time_
;
1042 syncer::ConnectionStatus connection_status_
;
1043 base::Time token_request_time_
;
1044 base::Time token_receive_time_
;
1045 GoogleServiceAuthError last_get_token_error_
;
1046 base::Time next_token_request_time_
;
1048 scoped_ptr
<sync_driver::LocalDeviceInfoProvider
> local_device_
;
1050 // Locally owned SyncableService implementations.
1051 scoped_ptr
<browser_sync::SessionsSyncManager
> sessions_sync_manager_
;
1052 scoped_ptr
<sync_driver::DeviceInfoSyncService
> device_info_sync_service_
;
1054 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
1056 scoped_ptr
<browser_sync::StartupController
> startup_controller_
;
1058 scoped_ptr
<browser_sync::BackupRollbackController
>
1059 backup_rollback_controller_
;
1061 // Mode of current backend.
1062 BackendMode backend_mode_
;
1064 // Whether backup is needed before sync starts.
1067 // Whether backup is finished.
1068 bool backup_finished_
;
1070 base::Time backup_start_time_
;
1073 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
1074 clear_browsing_data_
;
1076 // Last time when pre-sync data was saved. NULL pointer means backup data
1077 // state is unknown. If time value is null, backup data doesn't exist.
1078 scoped_ptr
<base::Time
> last_backup_time_
;
1080 BrowsingDataRemover::Observer
* browsing_data_remover_observer_
;
1082 // The full path to the sync data directory.
1083 base::FilePath directory_path_
;
1085 scoped_ptr
<browser_sync::SyncStoppedReporter
> sync_stopped_reporter_
;
1087 // Listens for the system being under memory pressure.
1088 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
1090 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
1092 // We don't use |weak_factory_| for the StartupController because the weak
1093 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1094 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1095 // StartupController an Unretained reference to future-proof against
1096 // the controller impl changing to post tasks. Therefore, we have a separate
1098 base::WeakPtrFactory
<ProfileSyncService
> startup_controller_weak_factory_
;
1100 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1103 bool ShouldShowActionOnUI(
1104 const syncer::SyncProtocolError
& error
);
1107 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_