1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
12 #include "base/basictypes.h"
13 #include "base/compiler_specific.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/location.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/strings/string16.h"
21 #include "base/time/time.h"
22 #include "base/timer/timer.h"
23 #include "chrome/browser/browsing_data/browsing_data_remover.h"
24 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
25 #include "chrome/browser/sync/backup_rollback_controller.h"
26 #include "chrome/browser/sync/glue/sync_backend_host.h"
27 #include "chrome/browser/sync/profile_sync_service_base.h"
28 #include "chrome/browser/sync/profile_sync_service_observer.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 "components/keyed_service/core/keyed_service.h"
33 #include "components/signin/core/browser/signin_manager_base.h"
34 #include "components/sync_driver/data_type_controller.h"
35 #include "components/sync_driver/data_type_encryption_handler.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 "google_apis/gaia/google_service_auth_error.h"
45 #include "google_apis/gaia/oauth2_token_service.h"
46 #include "net/base/backoff_entry.h"
47 #include "sync/internal_api/public/base/model_type.h"
48 #include "sync/internal_api/public/engine/model_safe_worker.h"
49 #include "sync/internal_api/public/shutdown_reason.h"
50 #include "sync/internal_api/public/sync_manager_factory.h"
51 #include "sync/internal_api/public/util/experiments.h"
52 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
53 #include "sync/js/sync_js_controller.h"
57 class ProfileOAuth2TokenService;
58 class ProfileSyncComponentsFactory;
59 class SupervisedUserSigninManagerWrapper;
60 class SyncErrorController;
61 class SyncTypePreferenceProvider;
67 namespace browser_sync {
68 class BackendMigrator;
71 class OpenTabsUIDelegate;
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 } // namespace sync_driver
86 class BaseTransaction;
87 class NetworkResources;
88 struct CommitCounters;
89 struct StatusCounters;
90 struct SyncCredentials;
91 struct UpdateCounters;
97 } // namespace sync_pb
99 // ProfileSyncService is the layer between browser subsystems like bookmarks,
100 // and the sync backend. Each subsystem is logically thought of as being
103 // Individual datatypes can, at any point, be in a variety of stages of being
104 // "enabled". Here are some specific terms for concepts used in this class:
106 // 'Registered' (feature suppression for a datatype)
108 // When a datatype is registered, the user has the option of syncing it.
109 // The sync opt-in UI will show only registered types; a checkbox should
110 // never be shown for an unregistered type, and nor should it ever be
113 // A datatype is considered registered once RegisterDataTypeController
114 // has been called with that datatype's DataTypeController.
116 // 'Preferred' (user preferences and opt-out for a datatype)
118 // This means the user's opt-in or opt-out preference on a per-datatype
119 // basis. The sync service will try to make active exactly these types.
120 // If a user has opted out of syncing a particular datatype, it will
121 // be registered, but not preferred.
123 // This state is controlled by the ConfigurePreferredDataTypes and
124 // GetPreferredDataTypes. They are stored in the preferences system,
125 // and persist; though if a datatype is not registered, it cannot
126 // be a preferred datatype.
128 // 'Active' (run-time initialization of sync system for a datatype)
130 // An active datatype is a preferred datatype that is actively being
131 // synchronized: the syncer has been instructed to querying the server
132 // for this datatype, first-time merges have finished, and there is an
133 // actively installed ChangeProcessor that listens for changes to this
134 // datatype, propagating such changes into and out of the sync backend
137 // When a datatype is in the process of becoming active, it may be
138 // in some intermediate state. Those finer-grained intermediate states
139 // are differentiated by the DataTypeController state.
141 // Sync Configuration:
143 // Sync configuration is accomplished via the following APIs:
144 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
145 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
146 // using the passed passphrase.
147 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
150 // Additionally, the current sync configuration can be fetched by calling
151 // * GetRegisteredDataTypes()
152 // * GetPreferredDataTypes()
153 // * GetActiveDataTypes()
154 // * IsUsingSecondaryPassphrase()
155 // * EncryptEverythingEnabled()
156 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
158 // The "sync everything" state cannot be read from ProfileSyncService, but
159 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
161 // Initial sync setup:
163 // For privacy reasons, it is usually desirable to avoid syncing any data
164 // types until the user has finished setting up sync. There are two APIs
165 // that control the initial sync download:
167 // * SetSyncSetupCompleted()
168 // * SetSetupInProgress()
170 // SetSyncSetupCompleted() should be called once the user has finished setting
171 // up sync at least once on their account. SetSetupInProgress(true) should be
172 // called while the user is actively configuring their account, and then
173 // SetSetupInProgress(false) should be called when configuration is complete.
174 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
175 // been called, then the sync engine knows not to download any user data.
177 // When initial sync is complete, the UI code should call
178 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
179 // tell the sync engine that setup is completed and it can begin downloading
180 // data from the sync server.
182 class ProfileSyncService : public ProfileSyncServiceBase,
183 public sync_driver::SyncFrontend,
184 public sync_driver::SyncPrefObserver,
185 public sync_driver::DataTypeManagerObserver,
186 public syncer::UnrecoverableErrorHandler,
188 public sync_driver::DataTypeEncryptionHandler,
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 // Used to specify the kind of passphrase with which sync data is encrypted.
241 enum PassphraseType {
242 IMPLICIT, // The user did not provide a custom passphrase for encryption.
243 // We implicitly use the GAIA password in such cases.
244 EXPLICIT, // The user selected the "use custom passphrase" radio button
245 // during sync setup and provided a passphrase.
248 enum SyncStatusSummary {
252 DATATYPES_NOT_INITIALIZED,
261 SYNC, // Backend for syncing.
262 BACKUP, // Backend for backup.
263 ROLLBACK // Backend for rollback.
266 // Default sync server URL.
267 static const char* kSyncServerUrl;
268 // Sync server URL for dev channel users
269 static const char* kDevServerUrl;
271 // Takes ownership of |factory| and |signin_wrapper|.
273 scoped_ptr<ProfileSyncComponentsFactory> factory,
275 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
276 ProfileOAuth2TokenService* oauth2_token_service,
277 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
278 virtual ~ProfileSyncService();
280 // Initializes the object. This must be called at most once, and
281 // immediately after an object of this class is constructed.
284 virtual void SetSyncSetupCompleted();
286 // ProfileSyncServiceBase implementation.
287 virtual bool HasSyncSetupCompleted() const OVERRIDE;
288 virtual bool ShouldPushChanges() OVERRIDE;
289 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
290 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
291 virtual void RemoveObserver(
292 ProfileSyncServiceBase::Observer* observer) OVERRIDE;
293 virtual bool HasObserver(
294 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. If DEVICE_INFO model type isn't yet
382 // enabled or syncing, returns NULL.
383 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
385 // Fills state_map with a map of current data types that are possible to
386 // sync, as well as their states.
387 void GetDataTypeControllerStates(
388 sync_driver::DataTypeController::StateMap* state_map) const;
390 // Disables sync for user. Use ShowLoginDialog to enable.
391 virtual void DisableForUser();
393 // Disables sync for the user and prevents it from starting on next restart.
394 virtual void StopSyncingPermanently();
396 // SyncFrontend implementation.
397 virtual void OnBackendInitialized(
398 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
399 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
401 const std::string& cache_guid,
402 bool success) OVERRIDE;
403 virtual void OnSyncCycleCompleted() OVERRIDE;
404 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
405 virtual void OnDirectoryTypeCommitCounterUpdated(
406 syncer::ModelType type,
407 const syncer::CommitCounters& counters) OVERRIDE;
408 virtual void OnDirectoryTypeUpdateCounterUpdated(
409 syncer::ModelType type,
410 const syncer::UpdateCounters& counters) OVERRIDE;
411 virtual void OnDirectoryTypeStatusCounterUpdated(
412 syncer::ModelType type,
413 const syncer::StatusCounters& counters) OVERRIDE;
414 virtual void OnSyncConfigureRetry() OVERRIDE;
415 virtual void OnConnectionStatusChange(
416 syncer::ConnectionStatus status) OVERRIDE;
417 virtual void OnPassphraseRequired(
418 syncer::PassphraseRequiredReason reason,
419 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
420 virtual void OnPassphraseAccepted() OVERRIDE;
421 virtual void OnEncryptedTypesChanged(
422 syncer::ModelTypeSet encrypted_types,
423 bool encrypt_everything) OVERRIDE;
424 virtual void OnEncryptionComplete() OVERRIDE;
425 virtual void OnMigrationNeededForTypes(
426 syncer::ModelTypeSet types) OVERRIDE;
427 virtual void OnExperimentsChanged(
428 const syncer::Experiments& experiments) OVERRIDE;
429 virtual void OnActionableError(
430 const syncer::SyncProtocolError& error) OVERRIDE;
432 // DataTypeManagerObserver implementation.
433 virtual void OnConfigureDone(
434 const sync_driver::DataTypeManager::ConfigureResult& result) OVERRIDE;
435 virtual void OnConfigureRetry() OVERRIDE;
436 virtual void OnConfigureStart() OVERRIDE;
438 // DataTypeEncryptionHandler implementation.
439 virtual bool IsPassphraseRequired() const OVERRIDE;
440 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
442 // SigninManagerBase::Observer implementation.
443 virtual void GoogleSigninSucceeded(const std::string& account_id,
444 const std::string& username,
445 const std::string& password) OVERRIDE;
446 virtual void GoogleSignedOut(const std::string& account_id,
447 const std::string& username) OVERRIDE;
449 // Called when a user chooses which data types to sync as part of the sync
450 // setup wizard. |sync_everything| represents whether they chose the
451 // "keep everything synced" option; if true, |chosen_types| will be ignored
452 // and all data types will be synced. |sync_everything| means "sync all
453 // current and future data types."
454 virtual void OnUserChoseDatatypes(bool sync_everything,
455 syncer::ModelTypeSet chosen_types);
457 // Get the sync status code.
458 SyncStatusSummary QuerySyncStatusSummary();
460 // Get a description of the sync status for displaying in the user interface.
461 std::string QuerySyncStatusSummaryString();
463 // Initializes a struct of status indicators with data from the backend.
464 // Returns false if the backend was not available for querying; in that case
465 // the struct will be filled with default data.
466 virtual bool QueryDetailedSyncStatus(
467 browser_sync::SyncBackendHost::Status* result);
469 virtual const GoogleServiceAuthError& GetAuthError() const;
471 // Returns true if initial sync setup is in progress (does not return true
472 // if the user is customizing sync after already completing setup once).
473 // ProfileSyncService uses this to determine if it's OK to start syncing, or
474 // if the user is still setting up the initial sync configuration.
475 virtual bool FirstSetupInProgress() const;
477 // Called by the UI to notify the ProfileSyncService that UI is visible so it
478 // will not start syncing. This tells sync whether it's safe to start
479 // downloading data types yet (we don't start syncing until after sync setup
480 // is complete). The UI calls this as soon as any part of the signin wizard is
481 // displayed (even just the login UI).
482 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
483 // that data download starts.
484 virtual void SetSetupInProgress(bool setup_in_progress);
486 // Returns true if the SyncBackendHost has told us it's ready to accept
488 // [REMARK] - it is safe to call this function only from the ui thread.
489 // because the variable is not thread safe and should only be accessed from
490 // single thread. If we want multiple threads to access this(and there is
491 // currently no need to do so) we need to protect this with a lock.
492 // TODO(timsteele): What happens if the bookmark model is loaded, a change
493 // takes place, and the backend isn't initialized yet?
494 virtual bool sync_initialized() const;
496 virtual bool HasUnrecoverableError() const;
497 const std::string& unrecoverable_error_message() {
498 return unrecoverable_error_message_;
500 tracked_objects::Location unrecoverable_error_location() {
501 return unrecoverable_error_location_;
504 // Returns true if OnPassphraseRequired has been called for decryption and
505 // we have an encrypted data type enabled.
506 virtual bool IsPassphraseRequiredForDecryption() const;
508 syncer::PassphraseRequiredReason passphrase_required_reason() const {
509 return passphrase_required_reason_;
512 // Returns a user-friendly string form of last synced time (in minutes).
513 virtual base::string16 GetLastSyncedTimeString() const;
515 // Returns a human readable string describing backend initialization state.
516 std::string GetBackendInitializationStateString() const;
518 // Returns true if startup is suppressed (i.e. user has stopped syncing via
519 // the google dashboard).
520 virtual bool IsStartSuppressed() const;
522 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
524 // The profile we are syncing for.
525 Profile* profile() const { return profile_; }
527 // Returns a weak pointer to the service's JsController.
528 // Overrideable for testing purposes.
529 virtual base::WeakPtr<syncer::JsController> GetJsController();
531 // Record stats on various events.
532 static void SyncEvent(SyncEventCodes code);
534 // Returns whether sync is enabled. Sync can be enabled/disabled both
535 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
536 // command-line switches).
537 // Profile::IsSyncAccessible() is probably a better signal than this function.
538 // This function can be called from any thread, and the implementation doesn't
539 // assume it's running on the UI thread.
540 static bool IsSyncEnabled();
542 // Returns whether sync is managed, i.e. controlled by configuration
543 // management. If so, the user is not allowed to configure sync.
544 virtual bool IsManaged() const;
546 // syncer::UnrecoverableErrorHandler implementation.
547 virtual void OnUnrecoverableError(
548 const tracked_objects::Location& from_here,
549 const std::string& message) OVERRIDE;
551 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
552 // not change the preferred state of a datatype, and is not persisted across
554 void ReenableDatatype(syncer::ModelType type);
556 // The functions below (until ActivateDataType()) should only be
557 // called if sync_initialized() is true.
559 // TODO(akalin): This is called mostly by ModelAssociators and
560 // tests. Figure out how to pass the handle to the ModelAssociators
561 // directly, figure out how to expose this to tests, and remove this
563 virtual syncer::UserShare* GetUserShare() const;
565 // TODO(akalin): These two functions are used only by
566 // ProfileSyncServiceHarness. Figure out a different way to expose
567 // this info to that class, and remove these functions.
569 virtual syncer::sessions::SyncSessionSnapshot
570 GetLastSessionSnapshot() const;
572 // Returns whether or not the underlying sync engine has made any
573 // local changes to items that have not yet been synced with the
575 bool HasUnsyncedItems() const;
577 // Used by ProfileSyncServiceHarness. May return NULL.
578 browser_sync::BackendMigrator* GetBackendMigratorForTest();
580 // Used by tests to inspect interaction with OAuth2TokenService.
581 bool IsRetryingAccessTokenFetchForTest() const;
583 // Used by tests to inspect the OAuth2 access tokens used by PSS.
584 std::string GetAccessTokenForTest() const;
586 // TODO(sync): This is only used in tests. Can we remove it?
587 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
589 // Returns a ListValue indicating the status of all registered types.
592 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
593 // where <name> is a type's name, <value> is a string providing details for
594 // the type's status, and <status> is one of "error", "warning" or "ok"
595 // depending on the type's current status.
597 // This function is used by about_sync_util.cc to help populate the about:sync
598 // page. It returns a ListValue rather than a DictionaryValue in part to make
599 // it easier to iterate over its elements when constructing that page.
600 base::Value* GetTypeStatusMap() const;
602 // Overridden by tests.
603 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
604 virtual void DeactivateDataType(syncer::ModelType type);
606 // SyncPrefObserver implementation.
607 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
609 // Changes which data types we're going to be syncing to |preferred_types|.
610 // If it is running, the DataTypeManager will be instructed to reconfigure
611 // the sync backend so that exactly these datatypes are actively synced. See
612 // class comment for more on what it means for a datatype to be Preferred.
613 virtual void ChangePreferredDataTypes(
614 syncer::ModelTypeSet preferred_types);
616 // Returns the set of types which are preferred for enabling. This is a
617 // superset of the active types (see GetActiveDataTypes()).
618 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
620 // Returns the set of directory types which are preferred for enabling.
621 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
623 // Returns the set of off-thread types which are preferred for enabling.
624 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
626 // Returns the set of types which are enforced programmatically and can not
627 // be disabled by the user.
628 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
630 // Gets the set of all data types that could be allowed (the set that
631 // should be advertised to the user). These will typically only change
632 // via a command-line option. See class comment for more on what it means
633 // for a datatype to be Registered.
634 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
636 // Gets the set of directory types which could be allowed.
637 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
639 // Gets the set of off-thread types which could be allowed.
640 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
642 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
643 // for sensitive data types. Caller must be holding a
644 // syncapi::BaseTransaction to ensure thread safety.
645 virtual bool IsCryptographerReady(
646 const syncer::BaseTransaction* trans) const;
648 // Returns true if a secondary (explicit) passphrase is being used. It is not
649 // legal to call this method before the backend is initialized.
650 virtual bool IsUsingSecondaryPassphrase() const;
652 // Returns the actual passphrase type being used for encryption.
653 virtual syncer::PassphraseType GetPassphraseType() const;
655 // Returns the time the current explicit passphrase (if any), was set.
656 // If no secondary passphrase is in use, or no time is available, returns an
658 virtual base::Time GetExplicitPassphraseTime() const;
660 // Note about setting passphrases: There are different scenarios under which
661 // we might want to apply a passphrase. It could be for first-time encryption,
662 // re-encryption, or for decryption by clients that sign in at a later time.
663 // In addition, encryption can either be done using a custom passphrase, or by
664 // reusing the GAIA password. Depending on what is happening in the system,
665 // callers should determine which of the two methods below must be used.
667 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
668 // specifies whether the passphrase is a custom passphrase or the GAIA
669 // password being reused as a passphrase.
670 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
671 // passphrase with this API.
672 virtual void SetEncryptionPassphrase(const std::string& passphrase,
673 PassphraseType type);
675 // Asynchronously decrypts pending keys using |passphrase|. Returns false
676 // immediately if the passphrase could not be used to decrypt a locally cached
677 // copy of encrypted keys; returns true otherwise.
678 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
681 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
682 // after calling this to force the encryption to occur.
683 virtual void EnableEncryptEverything();
685 // Returns true if we are currently set to encrypt all the sync data. Note:
686 // this is based on the cryptographer's settings, so if the user has recently
687 // requested encryption to be turned on, this may not be true yet. For that,
688 // encryption_pending() must be checked.
689 virtual bool EncryptEverythingEnabled() const;
691 // Returns true if the syncer is waiting for new datatypes to be encrypted.
692 virtual bool encryption_pending() const;
694 const GURL& sync_service_url() const { return sync_service_url_; }
695 SigninManagerBase* signin() const;
698 bool auto_start_enabled() const;
699 bool setup_in_progress() const;
701 // Stops the sync backend and sets the flag for suppressing sync startup.
702 void StopAndSuppress();
704 // Resets the flag for suppressing sync startup and starts the sync backend.
705 virtual void UnsuppressAndStart();
707 // Marks all currently registered types as "acknowledged" so we won't prompt
708 // the user about them any more.
709 void AcknowledgeSyncedTypes();
711 SyncErrorController* sync_error_controller() {
712 return sync_error_controller_.get();
715 // TODO(sync): This is only used in tests. Can we remove it?
716 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
718 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
719 return configure_status_;
722 // If true, the ProfileSyncService has detected that a new GAIA signin has
723 // succeeded, and is waiting for initialization to complete. This is used by
724 // the UI to differentiate between a new auth error (encountered as part of
725 // the initialization process) and a pre-existing auth error that just hasn't
726 // been cleared yet. Virtual for testing purposes.
727 virtual bool waiting_for_auth() const;
729 // The set of currently enabled sync experiments.
730 const syncer::Experiments& current_experiments() const;
732 // OAuth2TokenService::Consumer implementation.
733 virtual void OnGetTokenSuccess(
734 const OAuth2TokenService::Request* request,
735 const std::string& access_token,
736 const base::Time& expiration_time) OVERRIDE;
737 virtual void OnGetTokenFailure(
738 const OAuth2TokenService::Request* request,
739 const GoogleServiceAuthError& error) OVERRIDE;
741 // OAuth2TokenService::Observer implementation.
742 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
743 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
744 virtual void OnRefreshTokensLoaded() OVERRIDE;
746 // KeyedService implementation. This must be called exactly
747 // once (before this object is destroyed).
748 virtual void Shutdown() OVERRIDE;
750 // Called when a datatype (SyncableService) has a need for sync to start
751 // ASAP, presumably because a local change event has occurred but we're
752 // still in deferred start mode, meaning the SyncableService hasn't been
753 // told to MergeDataAndStartSyncing yet.
754 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
756 // Return sync token status.
757 SyncTokenStatus GetSyncTokenStatus() const;
759 browser_sync::FaviconCache* GetFaviconCache();
761 // Overrides the NetworkResources used for Sync connections.
762 // This function takes ownership of |network_resources|.
763 void OverrideNetworkResourcesForTest(
764 scoped_ptr<syncer::NetworkResources> network_resources);
766 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
768 BackendMode backend_mode() const {
769 return backend_mode_;
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;
785 // Helper to configure the priority data types.
786 void ConfigurePriorityDataTypes();
788 // Helper to install and configure a data type manager.
789 void ConfigureDataTypeManager();
791 // Shuts down the backend sync components.
792 // |reason| dictates if syncing is being disabled or not, and whether
793 // to claim ownership of sync thread from backend.
794 void ShutdownImpl(syncer::ShutdownReason reason);
796 // Return SyncCredentials from the OAuth2TokenService.
797 syncer::SyncCredentials GetCredentials();
799 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
801 const sync_driver::DataTypeController::TypeMap&
802 directory_data_type_controllers() {
803 return directory_data_type_controllers_;
806 // Helper method for managing encryption UI.
807 bool IsEncryptedDatatypeEnabled() const;
809 // Helper for OnUnrecoverableError.
810 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
811 // and in SyncBackendHost::Shutdown.
812 void OnUnrecoverableErrorImpl(
813 const tracked_objects::Location& from_here,
814 const std::string& message,
815 bool delete_sync_database);
817 virtual bool NeedBackup() const;
819 // This is a cache of the last authentication response we received from the
820 // sync server. The UI queries this to display appropriate messaging to the
822 GoogleServiceAuthError last_auth_error_;
824 // Our asynchronous backend to communicate with sync components living on
826 scoped_ptr<browser_sync::SyncBackendHost> backend_;
828 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
829 // was required for encryption, decryption with a cached passphrase, or
830 // because a new passphrase is required?
831 syncer::PassphraseRequiredReason passphrase_required_reason_;
834 enum UnrecoverableErrorReason {
837 ERROR_REASON_BACKEND_INIT_FAILURE,
838 ERROR_REASON_CONFIGURATION_RETRY,
839 ERROR_REASON_CONFIGURATION_FAILURE,
840 ERROR_REASON_ACTIONABLE_ERROR,
844 enum AuthErrorMetric {
845 AUTH_ERROR_ENCOUNTERED,
850 friend class ProfileSyncServicePasswordTest;
851 friend class SyncTest;
852 friend class TestProfileSyncService;
853 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
855 // Update the last auth error and notify observers of error state.
856 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
858 // Detects and attempts to recover from a previous improper datatype
859 // configuration where Keep Everything Synced and the preferred types were
860 // not correctly set.
861 void TrySyncDatatypePrefRecovery();
863 // Puts the backend's sync scheduler into NORMAL mode.
864 // Called when configuration is complete.
865 void StartSyncingWithServer();
867 // Called when we've determined that we don't need a passphrase (either
868 // because OnPassphraseAccepted() was called, or because we've gotten a
869 // OnPassphraseRequired() but no data types are enabled).
870 void ResolvePassphraseRequired();
872 // During initial signin, ProfileSyncService caches the user's signin
873 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
874 // This routine is invoked once the backend has started up to use the
875 // cached passphrase and clear it out when it is done.
876 void ConsumeCachedPassphraseIfPossible();
878 // RequestAccessToken initiates RPC to request downscoped access token from
879 // refresh token. This happens when a new OAuth2 login token is loaded and
880 // when sync server returns AUTH_ERROR which indicates it is time to refresh
882 virtual void RequestAccessToken();
884 // Return true if backend should start from a fresh sync DB.
885 bool ShouldDeleteSyncFolder();
887 // If |delete_sync_data_folder| is true, then this method will delete all
888 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
889 void InitializeBackend(bool delete_sync_data_folder);
891 // Initializes the various settings from the command line.
894 // Sets the last synced time to the current time.
895 void UpdateLastSyncedTime();
897 void NotifyObservers();
898 void NotifySyncCycleCompleted();
900 void ClearStaleErrors();
902 void ClearUnrecoverableError();
904 // Starts up the backend sync components. |mode| specifies the kind of
905 // backend to start, one of SYNC, BACKUP or ROLLBACK.
906 virtual void StartUpSlowBackendComponents(BackendMode mode);
908 // About-flags experiment names for datatypes that aren't enabled by default
910 static std::string GetExperimentNameForDataType(
911 syncer::ModelType data_type);
913 // Create and register a new datatype controller.
914 void RegisterNewDataType(syncer::ModelType data_type);
916 // Reconfigures the data type manager with the latest enabled types.
917 // Note: Does not initialize the backend if it is not already initialized.
918 // This function needs to be called only after sync has been initialized
919 // (i.e.,only for reconfigurations). The reason we don't initialize the
920 // backend is because if we had encountered an unrecoverable error we don't
921 // want to startup once more.
922 virtual void ReconfigureDatatypeManager();
924 // Collects preferred sync data types from |preference_providers_|.
925 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
927 // Called when the user changes the sync configuration, to update the UMA
929 void UpdateSelectedTypesHistogram(
930 bool sync_everything,
931 const syncer::ModelTypeSet chosen_types) const;
933 #if defined(OS_CHROMEOS)
934 // Refresh spare sync bootstrap token for re-enabling the sync service.
935 // Called on successful sign-in notifications.
936 void RefreshSpareBootstrapToken(const std::string& passphrase);
939 // Internal unrecoverable error handler. Used to track error reason via
940 // Sync.UnrecoverableErrors histogram.
941 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
942 const std::string& message,
943 bool delete_sync_database,
944 UnrecoverableErrorReason reason);
946 // Returns the type of manager to use according to |backend_mode_|.
947 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
949 // Update UMA for syncing backend.
950 void UpdateBackendInitUMA(bool success);
952 // Various setup following backend initialization, mostly for syncing backend.
953 void PostBackendInitialization();
955 // True if a syncing backend exists.
956 bool HasSyncingBackend() const;
958 // Update first sync time stored in preferences
959 void UpdateFirstSyncTimePref();
961 // Clear browsing data since first sync during rollback.
962 void ClearBrowsingDataSinceFirstSync();
964 // Post background task to check sync backup DB state if needed.
965 void CheckSyncBackupIfNeeded();
967 // Callback to receive backup DB check result.
968 void CheckSyncBackupCallback(base::Time backup_time);
970 // Callback function to call |startup_controller_|.TryStart() after
971 // backup/rollback finishes;
972 void TryStartSyncAfterBackup();
974 // Clean up prefs and backup DB when rollback is not needed.
975 void CleanUpBackup();
977 // Factory used to create various dependent objects.
978 scoped_ptr<ProfileSyncComponentsFactory> factory_;
980 // The profile whose data we are synchronizing.
983 // The class that handles getting, setting, and persisting sync
985 sync_driver::SyncPrefs sync_prefs_;
987 // TODO(ncarter): Put this in a profile, once there is UI for it.
988 // This specifies where to find the sync server.
989 const GURL sync_service_url_;
991 // The last time we detected a successful transition from SYNCING state.
992 // Our backend notifies us whenever we should take a new snapshot.
993 base::Time last_synced_time_;
995 // The time that OnConfigureStart is called. This member is zero if
996 // OnConfigureStart has not yet been called, and is reset to zero once
997 // OnConfigureDone is called.
998 base::Time sync_configure_start_time_;
1000 // Indicates if this is the first time sync is being configured. This value
1001 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
1002 bool is_first_time_sync_configure_;
1004 // List of available data type controllers for directory types.
1005 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
1007 // Whether the SyncBackendHost has been initialized.
1008 bool backend_initialized_;
1010 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1011 // ProfileSyncService from starting backend till browser restarted or user
1013 bool sync_disabled_by_admin_;
1015 // Set to true if a signin has completed but we're still waiting for the
1016 // backend to refresh its credentials.
1017 bool is_auth_in_progress_;
1019 // Encapsulates user signin - used to set/get the user's authenticated
1021 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
1023 // Information describing an unrecoverable error.
1024 UnrecoverableErrorReason unrecoverable_error_reason_;
1025 std::string unrecoverable_error_message_;
1026 tracked_objects::Location unrecoverable_error_location_;
1028 // Manages the start and stop of the directory data types.
1029 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
1031 // Manager for the non-blocking data types.
1032 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
1034 ObserverList<ProfileSyncServiceBase::Observer> observers_;
1035 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
1036 ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
1038 std::set<SyncTypePreferenceProvider*> preference_providers_;
1040 syncer::SyncJsController sync_js_controller_;
1042 // This allows us to gracefully handle an ABORTED return code from the
1043 // DataTypeManager in the event that the server informed us to cease and
1044 // desist syncing immediately.
1045 bool expect_sync_configuration_aborted_;
1047 // Sometimes we need to temporarily hold on to a passphrase because we don't
1048 // yet have a backend to send it to. This happens during initialization as
1049 // we don't StartUp until we have a valid token, which happens after valid
1050 // credentials were provided.
1051 std::string cached_passphrase_;
1053 // The current set of encrypted types. Always a superset of
1054 // syncer::Cryptographer::SensitiveTypes().
1055 syncer::ModelTypeSet encrypted_types_;
1057 // Whether we want to encrypt everything.
1058 bool encrypt_everything_;
1060 // Whether we're waiting for an attempt to encryption all sync data to
1061 // complete. We track this at this layer in order to allow the user to cancel
1062 // if they e.g. don't remember their explicit passphrase.
1063 bool encryption_pending_;
1065 scoped_ptr<browser_sync::BackendMigrator> migrator_;
1067 // This is the last |SyncProtocolError| we received from the server that had
1068 // an action set on it.
1069 syncer::SyncProtocolError last_actionable_error_;
1071 // Exposes sync errors to the UI.
1072 scoped_ptr<SyncErrorController> sync_error_controller_;
1074 // Tracks the set of failed data types (those that encounter an error
1075 // or must delay loading for some reason).
1076 sync_driver::DataTypeStatusTable data_type_status_table_;
1078 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
1080 // The set of currently enabled sync experiments.
1081 syncer::Experiments current_experiments_;
1083 // Sync's internal debug info listener. Used to record datatype configuration
1084 // and association information.
1085 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1087 // A thread where all the sync operations happen.
1089 // * Created when backend starts for the first time.
1090 // * If sync is disabled, PSS claims ownership from backend.
1091 // * If sync is reenabled, PSS passes ownership to new backend.
1092 scoped_ptr<base::Thread> sync_thread_;
1094 // ProfileSyncService uses this service to get access tokens.
1095 ProfileOAuth2TokenService* const oauth2_token_service_;
1097 // ProfileSyncService needs to remember access token in order to invalidate it
1098 // with OAuth2TokenService.
1099 std::string access_token_;
1101 // ProfileSyncService needs to hold reference to access_token_request_ for
1102 // the duration of request in order to receive callbacks.
1103 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1105 // If RequestAccessToken fails with transient error then retry requesting
1106 // access token with exponential backoff.
1107 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1108 net::BackoffEntry request_access_token_backoff_;
1110 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1112 // We don't use |weak_factory_| for the StartupController because the weak
1113 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1114 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1115 // StartupController an Unretained reference to future-proof against
1116 // the controller impl changing to post tasks. Therefore, we have a separate
1118 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1120 // States related to sync token and connection.
1121 base::Time connection_status_update_time_;
1122 syncer::ConnectionStatus connection_status_;
1123 base::Time token_request_time_;
1124 base::Time token_receive_time_;
1125 GoogleServiceAuthError last_get_token_error_;
1126 base::Time next_token_request_time_;
1128 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
1130 // Locally owned SyncableService implementations.
1131 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
1132 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
1134 scoped_ptr<syncer::NetworkResources> network_resources_;
1136 browser_sync::StartupController startup_controller_;
1138 browser_sync::BackupRollbackController backup_rollback_controller_;
1140 // Mode of current backend.
1141 BackendMode backend_mode_;
1143 // Whether backup is needed before sync starts.
1146 // Whether backup is finished.
1147 bool backup_finished_;
1149 base::Time backup_start_time_;
1152 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1153 clear_browsing_data_;
1155 // Last time when pre-sync data was saved. NULL pointer means backup data
1156 // state is unknown. If time value is null, backup data doesn't exist.
1157 scoped_ptr<base::Time> last_backup_time_;
1159 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1161 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1164 bool ShouldShowActionOnUI(
1165 const syncer::SyncProtocolError& error);
1168 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_