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
;
74 class SyncSessionSnapshot
;
75 } // namespace sessions
76 } // namespace browser_sync
78 namespace sync_driver
{
79 class ChangeProcessor
;
80 class DataTypeManager
;
81 class DeviceInfoSyncService
;
82 class LocalDeviceInfoProvider
;
83 class OpenTabsUIDelegate
;
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 // Takes ownership of |factory| and |signin_wrapper|.
260 scoped_ptr
<ProfileSyncComponentsFactory
> factory
,
262 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
263 ProfileOAuth2TokenService
* oauth2_token_service
,
264 browser_sync::ProfileSyncServiceStartBehavior start_behavior
);
265 ~ProfileSyncService() override
;
267 // Initializes the object. This must be called at most once, and
268 // immediately after an object of this class is constructed.
271 // sync_driver::SyncService implementation
272 bool HasSyncSetupCompleted() const override
;
273 bool IsSyncAllowed() const override
;
274 bool IsSyncActive() const override
;
275 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
) override
;
276 bool CanSyncStart() const override
;
277 void RequestStop(SyncStopDataFate data_fate
) override
;
278 void RequestStart() override
;
279 syncer::ModelTypeSet
GetActiveDataTypes() const override
;
280 syncer::ModelTypeSet
GetPreferredDataTypes() const override
;
281 void OnUserChoseDatatypes(bool sync_everything
,
282 syncer::ModelTypeSet chosen_types
) override
;
283 void SetSyncSetupCompleted() override
;
284 bool FirstSetupInProgress() const override
;
285 void SetSetupInProgress(bool setup_in_progress
) override
;
286 bool setup_in_progress() const override
;
287 bool ConfigurationDone() const override
;
288 const GoogleServiceAuthError
& GetAuthError() const override
;
289 bool HasUnrecoverableError() const override
;
290 bool backend_initialized() const override
;
291 sync_driver::OpenTabsUIDelegate
* GetOpenTabsUIDelegate() override
;
292 bool IsPassphraseRequiredForDecryption() const override
;
293 base::Time
GetExplicitPassphraseTime() const override
;
294 bool IsUsingSecondaryPassphrase() const override
;
295 void EnableEncryptEverything() override
;
296 void SetEncryptionPassphrase(const std::string
& passphrase
,
297 PassphraseType type
) override
;
298 bool SetDecryptionPassphrase(const std::string
& passphrase
) override
300 void AddObserver(sync_driver::SyncServiceObserver
* observer
) override
;
301 void RemoveObserver(sync_driver::SyncServiceObserver
* observer
) override
;
303 const sync_driver::SyncServiceObserver
* observer
) const override
;
305 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver
* observer
);
306 void RemoveProtocolEventObserver(
307 browser_sync::ProtocolEventObserver
* observer
);
309 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
310 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver
* observer
);
312 // Add a sync type preference provider. Each provider may only be added once.
313 void AddPreferenceProvider(SyncTypePreferenceProvider
* provider
);
314 // Remove a sync type preference provider. May only be called for providers
315 // that have been added. Providers must not remove themselves while being
317 void RemovePreferenceProvider(SyncTypePreferenceProvider
* provider
);
318 // Check whether a given sync type preference provider has been added.
319 bool HasPreferenceProvider(SyncTypePreferenceProvider
* provider
) const;
321 // Asynchronously fetches base::Value representations of all sync nodes and
322 // returns them to the specified callback on this thread.
324 // These requests can live a long time and return when you least expect it.
325 // For safety, the callback should be bound to some sort of WeakPtr<> or
328 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
330 void RegisterAuthNotifications();
331 void UnregisterAuthNotifications();
333 // Return whether OAuth2 refresh token is loaded and available for the backend
334 // to start up. Virtual to enable mocking in tests.
335 virtual bool IsOAuthRefreshTokenAvailable();
337 // Registers a data type controller with the sync service. This
338 // makes the data type controller available for use, it does not
339 // enable or activate the synchronization of the data type (see
340 // ActivateDataType). Takes ownership of the pointer.
341 void RegisterDataTypeController(
342 sync_driver::DataTypeController
* data_type_controller
);
344 // Registers a type whose sync storage will not be managed by the
345 // ProfileSyncService. It declares that this sync type may be activated at
346 // some point in the future. This function call does not enable or activate
347 // the syncing of this type
348 void RegisterNonBlockingType(syncer::ModelType type
);
350 // Called by a component that supports non-blocking sync when it is ready to
351 // initialize its connection to the sync backend.
353 // If policy allows for syncing this type (ie. it is "preferred"), then this
354 // should result in a message to enable syncing for this type when the sync
355 // backend is available. If the type is not to be synced, this should result
356 // in a message that allows the component to delete its local sync state.
357 void InitializeNonBlockingType(
358 syncer::ModelType type
,
359 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
360 const base::WeakPtr
<syncer::ModelTypeSyncProxyImpl
>& proxy
);
362 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
363 virtual browser_sync::SyncedWindowDelegatesGetter
*
364 GetSyncedWindowDelegatesGetter() const;
366 // Returns the SyncableService for syncer::SESSIONS.
367 virtual syncer::SyncableService
* GetSessionsSyncableService();
369 // Returns the SyncableService for syncer::DEVICE_INFO.
370 virtual syncer::SyncableService
* GetDeviceInfoSyncableService();
372 // Returns DeviceInfo provider for the local device.
373 virtual sync_driver::LocalDeviceInfoProvider
* GetLocalDeviceInfoProvider();
375 // Returns synced devices tracker.
376 virtual sync_driver::DeviceInfoTracker
* GetDeviceInfoTracker() const;
378 // Fills state_map with a map of current data types that are possible to
379 // sync, as well as their states.
380 void GetDataTypeControllerStates(
381 sync_driver::DataTypeController::StateMap
* state_map
) const;
383 // SyncFrontend implementation.
384 void OnBackendInitialized(
385 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
386 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
388 const std::string
& cache_guid
,
389 bool success
) override
;
390 void OnSyncCycleCompleted() override
;
391 void OnProtocolEvent(const syncer::ProtocolEvent
& event
) override
;
392 void OnDirectoryTypeCommitCounterUpdated(
393 syncer::ModelType type
,
394 const syncer::CommitCounters
& counters
) override
;
395 void OnDirectoryTypeUpdateCounterUpdated(
396 syncer::ModelType type
,
397 const syncer::UpdateCounters
& counters
) override
;
398 void OnDirectoryTypeStatusCounterUpdated(
399 syncer::ModelType type
,
400 const syncer::StatusCounters
& counters
) override
;
401 void OnConnectionStatusChange(syncer::ConnectionStatus status
) override
;
402 void OnPassphraseRequired(
403 syncer::PassphraseRequiredReason reason
,
404 const sync_pb::EncryptedData
& pending_keys
) override
;
405 void OnPassphraseAccepted() override
;
406 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types
,
407 bool encrypt_everything
) override
;
408 void OnEncryptionComplete() override
;
409 void OnMigrationNeededForTypes(syncer::ModelTypeSet types
) override
;
410 void OnExperimentsChanged(const syncer::Experiments
& experiments
) override
;
411 void OnActionableError(const syncer::SyncProtocolError
& error
) override
;
412 void OnLocalSetPassphraseEncryption(
413 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) override
;
415 // DataTypeManagerObserver implementation.
416 void OnConfigureDone(
417 const sync_driver::DataTypeManager::ConfigureResult
& result
) override
;
418 void OnConfigureStart() override
;
420 // DataTypeEncryptionHandler implementation.
421 bool IsPassphraseRequired() const override
;
422 syncer::ModelTypeSet
GetEncryptedDataTypes() const override
;
424 // SigninManagerBase::Observer implementation.
425 void GoogleSigninSucceeded(const std::string
& account_id
,
426 const std::string
& username
,
427 const std::string
& password
) override
;
428 void GoogleSignedOut(const std::string
& account_id
,
429 const std::string
& username
) override
;
431 // Get the sync status code.
432 SyncStatusSummary
QuerySyncStatusSummary();
434 // Get a description of the sync status for displaying in the user interface.
435 std::string
QuerySyncStatusSummaryString();
437 // Initializes a struct of status indicators with data from the backend.
438 // Returns false if the backend was not available for querying; in that case
439 // the struct will be filled with default data.
440 virtual bool QueryDetailedSyncStatus(
441 browser_sync::SyncBackendHost::Status
* result
);
443 // Reconfigures the data type manager with the latest enabled types.
444 // Note: Does not initialize the backend if it is not already initialized.
445 // This function needs to be called only after sync has been initialized
446 // (i.e.,only for reconfigurations). The reason we don't initialize the
447 // backend is because if we had encountered an unrecoverable error we don't
448 // want to startup once more.
449 // This function is called by |SetSetupInProgress|.
450 virtual void ReconfigureDatatypeManager();
452 const std::string
& unrecoverable_error_message() {
453 return unrecoverable_error_message_
;
455 tracked_objects::Location
unrecoverable_error_location() {
456 return unrecoverable_error_location_
;
459 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
460 return passphrase_required_reason_
;
463 // Returns a user-friendly string form of last synced time (in minutes).
464 virtual base::string16
GetLastSyncedTimeString() const;
466 // Returns a human readable string describing backend initialization state.
467 std::string
GetBackendInitializationStateString() const;
469 // Returns true if sync is requested to be running by the user.
470 // Note that this does not mean that sync WILL be running; e.g. if
471 // IsSyncAllowed() is false then sync won't start, and if the user
472 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
473 // never become active. Use IsSyncActive to see if sync is running.
474 virtual bool IsSyncRequested() const;
476 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
478 // The profile we are syncing for.
479 Profile
* profile() const { return profile_
; }
481 // Returns a weak pointer to the service's JsController.
482 // Overrideable for testing purposes.
483 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
485 // Record stats on various events.
486 static void SyncEvent(SyncEventCodes code
);
488 // Returns whether sync is allowed to run based on command-line switches.
489 // Profile::IsSyncAllowed() is probably a better signal than this function.
490 // This function can be called from any thread, and the implementation doesn't
491 // assume it's running on the UI thread.
492 static bool IsSyncAllowedByFlag();
494 // Returns whether sync is managed, i.e. controlled by configuration
495 // management. If so, the user is not allowed to configure sync.
496 virtual bool IsManaged() const;
498 // syncer::UnrecoverableErrorHandler implementation.
499 void OnUnrecoverableError(const tracked_objects::Location
& from_here
,
500 const std::string
& message
) override
;
502 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
503 // not change the preferred state of a datatype, and is not persisted across
505 void ReenableDatatype(syncer::ModelType type
);
507 // The functions below (until ActivateDataType()) should only be
508 // called if backend_initialized() is true.
510 // TODO(akalin): This is called mostly by ModelAssociators and
511 // tests. Figure out how to pass the handle to the ModelAssociators
512 // directly, figure out how to expose this to tests, and remove this
514 virtual syncer::UserShare
* GetUserShare() const;
516 // TODO(akalin): These two functions are used only by
517 // ProfileSyncServiceHarness. Figure out a different way to expose
518 // this info to that class, and remove these functions.
520 virtual syncer::sessions::SyncSessionSnapshot
521 GetLastSessionSnapshot() const;
523 // Returns whether or not the underlying sync engine has made any
524 // local changes to items that have not yet been synced with the
526 bool HasUnsyncedItems() const;
528 // Used by ProfileSyncServiceHarness. May return NULL.
529 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
531 // Used by tests to inspect interaction with OAuth2TokenService.
532 bool IsRetryingAccessTokenFetchForTest() const;
534 // Used by tests to inspect the OAuth2 access tokens used by PSS.
535 std::string
GetAccessTokenForTest() const;
537 // TODO(sync): This is only used in tests. Can we remove it?
538 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
540 // Returns a ListValue indicating the status of all registered types.
543 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
544 // where <name> is a type's name, <value> is a string providing details for
545 // the type's status, and <status> is one of "error", "warning" or "ok"
546 // depending on the type's current status.
548 // This function is used by about_sync_util.cc to help populate the about:sync
549 // page. It returns a ListValue rather than a DictionaryValue in part to make
550 // it easier to iterate over its elements when constructing that page.
551 base::Value
* GetTypeStatusMap() const;
553 // Overridden by tests.
554 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
555 virtual void DeactivateDataType(syncer::ModelType type
);
557 // SyncPrefObserver implementation.
558 void OnSyncManagedPrefChange(bool is_sync_managed
) override
;
560 // Changes which data types we're going to be syncing to |preferred_types|.
561 // If it is running, the DataTypeManager will be instructed to reconfigure
562 // the sync backend so that exactly these datatypes are actively synced. See
563 // class comment for more on what it means for a datatype to be Preferred.
564 virtual void ChangePreferredDataTypes(
565 syncer::ModelTypeSet preferred_types
);
567 // Returns the set of directory types which are preferred for enabling.
568 virtual syncer::ModelTypeSet
GetPreferredDirectoryDataTypes() const;
570 // Returns the set of off-thread types which are preferred for enabling.
571 virtual syncer::ModelTypeSet
GetPreferredNonBlockingDataTypes() const;
573 // Returns the set of types which are enforced programmatically and can not
574 // be disabled by the user.
575 virtual syncer::ModelTypeSet
GetForcedDataTypes() const;
577 // Gets the set of all data types that could be allowed (the set that
578 // should be advertised to the user). These will typically only change
579 // via a command-line option. See class comment for more on what it means
580 // for a datatype to be Registered.
581 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
583 // Gets the set of directory types which could be allowed.
584 virtual syncer::ModelTypeSet
GetRegisteredDirectoryDataTypes() const;
586 // Gets the set of off-thread types which could be allowed.
587 virtual syncer::ModelTypeSet
GetRegisteredNonBlockingDataTypes() const;
589 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
590 // for sensitive data types. Caller must be holding a
591 // syncapi::BaseTransaction to ensure thread safety.
592 virtual bool IsCryptographerReady(
593 const syncer::BaseTransaction
* trans
) const;
595 // Returns the actual passphrase type being used for encryption.
596 virtual syncer::PassphraseType
GetPassphraseType() const;
598 // Note about setting passphrases: There are different scenarios under which
599 // we might want to apply a passphrase. It could be for first-time encryption,
600 // re-encryption, or for decryption by clients that sign in at a later time.
601 // In addition, encryption can either be done using a custom passphrase, or by
602 // reusing the GAIA password. Depending on what is happening in the system,
603 // callers should determine which of the two methods below must be used.
605 // Returns true if encrypting all the sync data is allowed. If this method
606 // returns false, EnableEncryptEverything() should not be called.
607 virtual bool EncryptEverythingAllowed() const;
609 // Sets whether encrypting all the sync data is allowed or not.
610 virtual void SetEncryptEverythingAllowed(bool allowed
);
612 // Returns true if we are currently set to encrypt all the sync data. Note:
613 // this is based on the cryptographer's settings, so if the user has recently
614 // requested encryption to be turned on, this may not be true yet. For that,
615 // encryption_pending() must be checked.
616 virtual bool EncryptEverythingEnabled() const;
618 // Returns true if the syncer is waiting for new datatypes to be encrypted.
619 virtual bool encryption_pending() const;
621 const GURL
& sync_service_url() const { return sync_service_url_
; }
622 SigninManagerBase
* signin() const;
625 bool auto_start_enabled() const;
627 SyncErrorController
* sync_error_controller() {
628 return sync_error_controller_
.get();
631 // TODO(sync): This is only used in tests. Can we remove it?
632 const sync_driver::DataTypeStatusTable
& data_type_status_table() const;
634 sync_driver::DataTypeManager::ConfigureStatus
configure_status() {
635 return configure_status_
;
638 // If true, the ProfileSyncService has detected that a new GAIA signin has
639 // succeeded, and is waiting for initialization to complete. This is used by
640 // the UI to differentiate between a new auth error (encountered as part of
641 // the initialization process) and a pre-existing auth error that just hasn't
642 // been cleared yet. Virtual for testing purposes.
643 virtual bool waiting_for_auth() const;
645 // The set of currently enabled sync experiments.
646 const syncer::Experiments
& current_experiments() const;
648 // OAuth2TokenService::Consumer implementation.
649 void OnGetTokenSuccess(const OAuth2TokenService::Request
* request
,
650 const std::string
& access_token
,
651 const base::Time
& expiration_time
) override
;
652 void OnGetTokenFailure(const OAuth2TokenService::Request
* request
,
653 const GoogleServiceAuthError
& error
) override
;
655 // OAuth2TokenService::Observer implementation.
656 void OnRefreshTokenAvailable(const std::string
& account_id
) override
;
657 void OnRefreshTokenRevoked(const std::string
& account_id
) override
;
658 void OnRefreshTokensLoaded() override
;
660 // KeyedService implementation. This must be called exactly
661 // once (before this object is destroyed).
662 void Shutdown() override
;
664 // Return sync token status.
665 SyncTokenStatus
GetSyncTokenStatus() const;
667 browser_sync::FaviconCache
* GetFaviconCache();
669 // Overrides the NetworkResources used for Sync connections.
670 // This function takes ownership of |network_resources|.
671 void OverrideNetworkResourcesForTest(
672 scoped_ptr
<syncer::NetworkResources
> network_resources
);
674 virtual bool IsDataTypeControllerRunning(syncer::ModelType type
) const;
676 // Returns the current mode the backend is in.
677 BackendMode
backend_mode() const;
679 // Helpers for testing rollback.
680 void SetBrowsingDataRemoverObserverForTesting(
681 BrowsingDataRemover::Observer
* observer
);
682 void SetClearingBrowseringDataForTesting(base::Callback
<
683 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
686 base::Time
GetDeviceBackupTimeForTesting() const;
688 // This triggers a Directory::SaveChanges() call on the sync thread.
689 // It should be used to persist data to disk when the process might be
690 // killed in the near future.
691 void FlushDirectory() const;
693 // Needed to test whether the directory is deleted properly.
694 base::FilePath
GetDirectoryPathForTest() const;
696 // Sometimes we need to wait for tasks on the sync thread in tests.
697 base::MessageLoop
* GetSyncLoopForTest() const;
699 // Triggers sync cycle with request to update specified |types|.
700 void RefreshTypesForTest(syncer::ModelTypeSet types
);
703 // Helper to install and configure a data type manager.
704 void ConfigureDataTypeManager();
706 // Shuts down the backend sync components.
707 // |reason| dictates if syncing is being disabled or not, and whether
708 // to claim ownership of sync thread from backend.
709 void ShutdownImpl(syncer::ShutdownReason reason
);
711 // Return SyncCredentials from the OAuth2TokenService.
712 syncer::SyncCredentials
GetCredentials();
714 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
716 const sync_driver::DataTypeController::TypeMap
&
717 directory_data_type_controllers() {
718 return directory_data_type_controllers_
;
721 // Helper method for managing encryption UI.
722 bool IsEncryptedDatatypeEnabled() const;
724 // Helper for OnUnrecoverableError.
725 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
726 // and in SyncBackendHost::Shutdown.
727 void OnUnrecoverableErrorImpl(
728 const tracked_objects::Location
& from_here
,
729 const std::string
& message
,
730 bool delete_sync_database
);
732 virtual bool NeedBackup() const;
734 // This is a cache of the last authentication response we received from the
735 // sync server. The UI queries this to display appropriate messaging to the
737 GoogleServiceAuthError last_auth_error_
;
739 // Our asynchronous backend to communicate with sync components living on
741 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
743 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
744 // was required for encryption, decryption with a cached passphrase, or
745 // because a new passphrase is required?
746 syncer::PassphraseRequiredReason passphrase_required_reason_
;
749 enum UnrecoverableErrorReason
{
752 ERROR_REASON_BACKEND_INIT_FAILURE
,
753 ERROR_REASON_CONFIGURATION_RETRY
,
754 ERROR_REASON_CONFIGURATION_FAILURE
,
755 ERROR_REASON_ACTIONABLE_ERROR
,
759 enum AuthErrorMetric
{
760 AUTH_ERROR_ENCOUNTERED
,
765 friend class ProfileSyncServicePasswordTest
;
766 friend class SyncTest
;
767 friend class TestProfileSyncService
;
768 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
770 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
771 // RequestStop for that. |data_fate| controls whether the local sync data is
772 // deleted or kept when the engine shuts down.
773 void StopImpl(SyncStopDataFate data_fate
);
775 // Update the last auth error and notify observers of error state.
776 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
778 // Detects and attempts to recover from a previous improper datatype
779 // configuration where Keep Everything Synced and the preferred types were
780 // not correctly set.
781 void TrySyncDatatypePrefRecovery();
783 // Puts the backend's sync scheduler into NORMAL mode.
784 // Called when configuration is complete.
785 void StartSyncingWithServer();
787 // Called when we've determined that we don't need a passphrase (either
788 // because OnPassphraseAccepted() was called, or because we've gotten a
789 // OnPassphraseRequired() but no data types are enabled).
790 void ResolvePassphraseRequired();
792 // During initial signin, ProfileSyncService caches the user's signin
793 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
794 // This routine is invoked once the backend has started up to use the
795 // cached passphrase and clear it out when it is done.
796 void ConsumeCachedPassphraseIfPossible();
798 // RequestAccessToken initiates RPC to request downscoped access token from
799 // refresh token. This happens when a new OAuth2 login token is loaded and
800 // when sync server returns AUTH_ERROR which indicates it is time to refresh
802 virtual void RequestAccessToken();
804 // Return true if backend should start from a fresh sync DB.
805 bool ShouldDeleteSyncFolder();
807 // If |delete_sync_data_folder| is true, then this method will delete all
808 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
809 void InitializeBackend(bool delete_sync_data_folder
);
811 // Initializes the various settings from the command line.
814 // Sets the last synced time to the current time.
815 void UpdateLastSyncedTime();
817 void NotifyObservers();
818 void NotifySyncCycleCompleted();
820 void ClearStaleErrors();
822 void ClearUnrecoverableError();
824 // Starts up the backend sync components. |mode| specifies the kind of
825 // backend to start, one of SYNC, BACKUP or ROLLBACK.
826 virtual void StartUpSlowBackendComponents(BackendMode mode
);
828 // Collects preferred sync data types from |preference_providers_|.
829 syncer::ModelTypeSet
GetDataTypesFromPreferenceProviders() const;
831 // Called when the user changes the sync configuration, to update the UMA
833 void UpdateSelectedTypesHistogram(
834 bool sync_everything
,
835 const syncer::ModelTypeSet chosen_types
) const;
837 #if defined(OS_CHROMEOS)
838 // Refresh spare sync bootstrap token for re-enabling the sync service.
839 // Called on successful sign-in notifications.
840 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
843 // Internal unrecoverable error handler. Used to track error reason via
844 // Sync.UnrecoverableErrors histogram.
845 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
846 const std::string
& message
,
847 bool delete_sync_database
,
848 UnrecoverableErrorReason reason
);
850 // Returns the type of manager to use according to |backend_mode_|.
851 syncer::SyncManagerFactory::MANAGER_TYPE
GetManagerType() const;
853 // Update UMA for syncing backend.
854 void UpdateBackendInitUMA(bool success
);
856 // Various setup following backend initialization, mostly for syncing backend.
857 void PostBackendInitialization();
859 // Whether sync has been authenticated with an account ID.
860 bool IsSignedIn() const;
862 // True if a syncing backend exists.
863 bool HasSyncingBackend() const;
865 // Update first sync time stored in preferences
866 void UpdateFirstSyncTimePref();
868 // Clear browsing data since first sync during rollback.
869 void ClearBrowsingDataSinceFirstSync();
871 // Post background task to check sync backup DB state if needed.
872 void CheckSyncBackupIfNeeded();
874 // Callback to receive backup DB check result.
875 void CheckSyncBackupCallback(base::Time backup_time
);
877 // Callback function to call |startup_controller_|.TryStart() after
878 // backup/rollback finishes;
879 void TryStartSyncAfterBackup();
881 // Clean up prefs and backup DB when rollback is not needed.
882 void CleanUpBackup();
884 // Tell the sync server that this client has disabled sync.
885 void RemoveClientFromServer() const;
887 // Called when the system is under memory pressure.
888 void OnMemoryPressure(
889 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
);
891 // Check if previous shutdown is shutdown cleanly.
892 void ReportPreviousSessionMemoryWarningCount();
894 // Factory used to create various dependent objects.
895 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
897 // The profile whose data we are synchronizing.
900 // The class that handles getting, setting, and persisting sync
902 sync_driver::SyncPrefs sync_prefs_
;
904 // TODO(ncarter): Put this in a profile, once there is UI for it.
905 // This specifies where to find the sync server.
906 const GURL sync_service_url_
;
908 // The time that OnConfigureStart is called. This member is zero if
909 // OnConfigureStart has not yet been called, and is reset to zero once
910 // OnConfigureDone is called.
911 base::Time sync_configure_start_time_
;
913 // Indicates if this is the first time sync is being configured. This value
914 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
915 bool is_first_time_sync_configure_
;
917 // List of available data type controllers for directory types.
918 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_
;
920 // Whether the SyncBackendHost has been initialized.
921 bool backend_initialized_
;
923 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
924 // ProfileSyncService from starting backend till browser restarted or user
926 bool sync_disabled_by_admin_
;
928 // Set to true if a signin has completed but we're still waiting for the
929 // backend to refresh its credentials.
930 bool is_auth_in_progress_
;
932 // Encapsulates user signin - used to set/get the user's authenticated
934 const scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_
;
936 // Information describing an unrecoverable error.
937 UnrecoverableErrorReason unrecoverable_error_reason_
;
938 std::string unrecoverable_error_message_
;
939 tracked_objects::Location unrecoverable_error_location_
;
941 // Manages the start and stop of the directory data types.
942 scoped_ptr
<sync_driver::DataTypeManager
> directory_data_type_manager_
;
944 // Manager for the non-blocking data types.
945 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_
;
947 base::ObserverList
<sync_driver::SyncServiceObserver
> observers_
;
948 base::ObserverList
<browser_sync::ProtocolEventObserver
>
949 protocol_event_observers_
;
950 base::ObserverList
<syncer::TypeDebugInfoObserver
> type_debug_info_observers_
;
952 std::set
<SyncTypePreferenceProvider
*> preference_providers_
;
954 syncer::SyncJsController sync_js_controller_
;
956 // This allows us to gracefully handle an ABORTED return code from the
957 // DataTypeManager in the event that the server informed us to cease and
958 // desist syncing immediately.
959 bool expect_sync_configuration_aborted_
;
961 // Sometimes we need to temporarily hold on to a passphrase because we don't
962 // yet have a backend to send it to. This happens during initialization as
963 // we don't StartUp until we have a valid token, which happens after valid
964 // credentials were provided.
965 std::string cached_passphrase_
;
967 // The current set of encrypted types. Always a superset of
968 // syncer::Cryptographer::SensitiveTypes().
969 syncer::ModelTypeSet encrypted_types_
;
971 // Whether encrypting everything is allowed.
972 bool encrypt_everything_allowed_
;
974 // Whether we want to encrypt everything.
975 bool encrypt_everything_
;
977 // Whether we're waiting for an attempt to encryption all sync data to
978 // complete. We track this at this layer in order to allow the user to cancel
979 // if they e.g. don't remember their explicit passphrase.
980 bool encryption_pending_
;
982 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
984 // This is the last |SyncProtocolError| we received from the server that had
985 // an action set on it.
986 syncer::SyncProtocolError last_actionable_error_
;
988 // Exposes sync errors to the UI.
989 scoped_ptr
<SyncErrorController
> sync_error_controller_
;
991 // Tracks the set of failed data types (those that encounter an error
992 // or must delay loading for some reason).
993 sync_driver::DataTypeStatusTable data_type_status_table_
;
995 sync_driver::DataTypeManager::ConfigureStatus configure_status_
;
997 // The set of currently enabled sync experiments.
998 syncer::Experiments current_experiments_
;
1000 // Sync's internal debug info listener. Used to record datatype configuration
1001 // and association information.
1002 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
1004 // A thread where all the sync operations happen.
1006 // * Created when backend starts for the first time.
1007 // * If sync is disabled, PSS claims ownership from backend.
1008 // * If sync is reenabled, PSS passes ownership to new backend.
1009 scoped_ptr
<base::Thread
> sync_thread_
;
1011 // ProfileSyncService uses this service to get access tokens.
1012 ProfileOAuth2TokenService
* const oauth2_token_service_
;
1014 // ProfileSyncService needs to remember access token in order to invalidate it
1015 // with OAuth2TokenService.
1016 std::string access_token_
;
1018 // ProfileSyncService needs to hold reference to access_token_request_ for
1019 // the duration of request in order to receive callbacks.
1020 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
1022 // If RequestAccessToken fails with transient error then retry requesting
1023 // access token with exponential backoff.
1024 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
1025 net::BackoffEntry request_access_token_backoff_
;
1027 // States related to sync token and connection.
1028 base::Time connection_status_update_time_
;
1029 syncer::ConnectionStatus connection_status_
;
1030 base::Time token_request_time_
;
1031 base::Time token_receive_time_
;
1032 GoogleServiceAuthError last_get_token_error_
;
1033 base::Time next_token_request_time_
;
1035 scoped_ptr
<sync_driver::LocalDeviceInfoProvider
> local_device_
;
1037 // Locally owned SyncableService implementations.
1038 scoped_ptr
<browser_sync::SessionsSyncManager
> sessions_sync_manager_
;
1039 scoped_ptr
<sync_driver::DeviceInfoSyncService
> device_info_sync_service_
;
1041 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
1043 scoped_ptr
<browser_sync::StartupController
> startup_controller_
;
1045 scoped_ptr
<browser_sync::BackupRollbackController
>
1046 backup_rollback_controller_
;
1048 // Mode of current backend.
1049 BackendMode backend_mode_
;
1051 // Whether backup is needed before sync starts.
1054 // Whether backup is finished.
1055 bool backup_finished_
;
1057 base::Time backup_start_time_
;
1060 void(BrowsingDataRemover::Observer
*, Profile
*, base::Time
, base::Time
)>
1061 clear_browsing_data_
;
1063 // Last time when pre-sync data was saved. NULL pointer means backup data
1064 // state is unknown. If time value is null, backup data doesn't exist.
1065 scoped_ptr
<base::Time
> last_backup_time_
;
1067 BrowsingDataRemover::Observer
* browsing_data_remover_observer_
;
1069 // The full path to the sync data directory.
1070 base::FilePath directory_path_
;
1072 scoped_ptr
<browser_sync::SyncStoppedReporter
> sync_stopped_reporter_
;
1074 // Listens for the system being under memory pressure.
1075 scoped_ptr
<base::MemoryPressureListener
> memory_pressure_listener_
;
1077 // Used to save/restore nigori state across backend instances. May be null.
1078 scoped_ptr
<syncer::SyncEncryptionHandler::NigoriState
> saved_nigori_state_
;
1080 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
1082 // We don't use |weak_factory_| for the StartupController because the weak
1083 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1084 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1085 // StartupController an Unretained reference to future-proof against
1086 // the controller impl changing to post tasks. Therefore, we have a separate
1088 base::WeakPtrFactory
<ProfileSyncService
> startup_controller_weak_factory_
;
1090 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1093 bool ShouldShowActionOnUI(
1094 const syncer::SyncProtocolError
& error
);
1097 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_