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/sync/backend_unrecoverable_error_handler.h"
24 #include "chrome/browser/sync/backup_rollback_controller.h"
25 #include "chrome/browser/sync/glue/local_device_info_provider.h"
26 #include "chrome/browser/sync/glue/sync_backend_host.h"
27 #include "chrome/browser/sync/glue/synced_device_tracker.h"
28 #include "chrome/browser/sync/profile_sync_service_base.h"
29 #include "chrome/browser/sync/profile_sync_service_observer.h"
30 #include "chrome/browser/sync/protocol_event_observer.h"
31 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
32 #include "chrome/browser/sync/startup_controller.h"
33 #include "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_encryption_handler.h"
37 #include "components/sync_driver/data_type_manager.h"
38 #include "components/sync_driver/data_type_manager_observer.h"
39 #include "components/sync_driver/failed_data_types_handler.h"
40 #include "components/sync_driver/non_blocking_data_type_manager.h"
41 #include "components/sync_driver/sync_frontend.h"
42 #include "components/sync_driver/sync_prefs.h"
43 #include "google_apis/gaia/google_service_auth_error.h"
44 #include "google_apis/gaia/oauth2_token_service.h"
45 #include "net/base/backoff_entry.h"
46 #include "sync/internal_api/public/base/model_type.h"
47 #include "sync/internal_api/public/engine/model_safe_worker.h"
48 #include "sync/internal_api/public/shutdown_reason.h"
49 #include "sync/internal_api/public/sync_manager_factory.h"
50 #include "sync/internal_api/public/util/experiments.h"
51 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
52 #include "sync/js/sync_js_controller.h"
56 class ProfileOAuth2TokenService;
57 class ProfileSyncComponentsFactory;
58 class SupervisedUserSigninManagerWrapper;
59 class SyncErrorController;
60 class SyncTypePreferenceProvider;
66 namespace browser_sync {
67 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 } // namespace sync_driver
84 class BaseTransaction;
85 class NetworkResources;
86 struct CommitCounters;
87 struct StatusCounters;
88 struct SyncCredentials;
89 struct UpdateCounters;
95 } // namespace sync_pb
97 using browser_sync::LocalDeviceInfoProvider;
98 using browser_sync::SessionsSyncManager;
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 ProfileSyncServiceBase,
184 public sync_driver::SyncFrontend,
185 public sync_driver::SyncPrefObserver,
186 public sync_driver::DataTypeManagerObserver,
187 public syncer::UnrecoverableErrorHandler,
189 public sync_driver::DataTypeEncryptionHandler,
190 public OAuth2TokenService::Consumer,
191 public OAuth2TokenService::Observer,
192 public SigninManagerBase::Observer {
194 typedef browser_sync::SyncBackendHost::Status Status;
196 // Status of sync server connection, sync token and token request.
197 struct SyncTokenStatus {
201 // Sync server connection status reported by sync backend.
202 base::Time connection_status_update_time;
203 syncer::ConnectionStatus connection_status;
205 // Times when OAuth2 access token is requested and received.
206 base::Time token_request_time;
207 base::Time token_receive_time;
209 // Error returned by OAuth2TokenService for token request and time when
210 // next request is scheduled.
211 GoogleServiceAuthError last_get_token_error;
212 base::Time next_token_request_time;
215 enum SyncEventCodes {
216 MIN_SYNC_EVENT_CODE = 0,
218 // Events starting the sync service.
219 START_FROM_NTP = 1, // Sync was started from the ad in NTP
220 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
221 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
222 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
223 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
224 START_FROM_URL = 6, // Sync was started from a typed URL.
226 // Events regarding cancellation of the signon process of sync.
227 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
228 // username and password.
229 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
230 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
231 // types and clicking OK.
232 // Events resulting in the stoppage of sync service.
233 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
234 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
236 // Miscellaneous events caused by sync service.
241 // Used to specify the kind of passphrase with which sync data is encrypted.
242 enum PassphraseType {
243 IMPLICIT, // The user did not provide a custom passphrase for encryption.
244 // We implicitly use the GAIA password in such cases.
245 EXPLICIT, // The user selected the "use custom passphrase" radio button
246 // during sync setup and provided a passphrase.
249 enum SyncStatusSummary {
253 DATATYPES_NOT_INITIALIZED,
262 SYNC, // Backend for syncing.
263 BACKUP, // Backend for backup.
264 ROLLBACK // Backend for rollback.
267 // Default sync server URL.
268 static const char* kSyncServerUrl;
269 // Sync server URL for dev channel users
270 static const char* kDevServerUrl;
272 // Takes ownership of |factory| and |signin_wrapper|.
274 scoped_ptr<ProfileSyncComponentsFactory> factory,
276 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
277 ProfileOAuth2TokenService* oauth2_token_service,
278 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
279 virtual ~ProfileSyncService();
281 // Initializes the object. This must be called at most once, and
282 // immediately after an object of this class is constructed.
285 virtual void SetSyncSetupCompleted();
287 // ProfileSyncServiceBase implementation.
288 virtual bool HasSyncSetupCompleted() const OVERRIDE;
289 virtual bool ShouldPushChanges() OVERRIDE;
290 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
291 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
292 virtual void RemoveObserver(
293 ProfileSyncServiceBase::Observer* observer) OVERRIDE;
294 virtual bool HasObserver(
295 ProfileSyncServiceBase::Observer* observer) const OVERRIDE;
298 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
299 void RemoveProtocolEventObserver(
300 browser_sync::ProtocolEventObserver* observer);
302 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
303 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
305 // Add a sync type preference provider. Each provider may only be added once.
306 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
307 // Remove a sync type preference provider. May only be called for providers
308 // that have been added. Providers must not remove themselves while being
310 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
311 // Check whether a given sync type preference provider has been added.
312 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
314 // Asynchronously fetches base::Value representations of all sync nodes and
315 // returns them to the specified callback on this thread.
317 // These requests can live a long time and return when you least expect it.
318 // For safety, the callback should be bound to some sort of WeakPtr<> or
321 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
323 void RegisterAuthNotifications();
324 void UnregisterAuthNotifications();
326 // Returns true if sync is enabled/not suppressed and the user is logged in.
327 // (being logged in does not mean that tokens are available - tokens may
328 // be missing because they have not loaded yet, or because they were deleted
329 // due to http://crbug.com/121755).
330 // Virtual to enable mocking in tests.
331 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
332 // callers use a seemingly arbitrary / redundant / bug prone combination of
333 // this method, IsSyncAccessible, and others.
334 virtual bool IsSyncEnabledAndLoggedIn();
336 // Return whether OAuth2 refresh token is loaded and available for the backend
337 // to start up. Virtual to enable mocking in tests.
338 virtual bool IsOAuthRefreshTokenAvailable();
340 // Registers a data type controller with the sync service. This
341 // makes the data type controller available for use, it does not
342 // enable or activate the synchronization of the data type (see
343 // ActivateDataType). Takes ownership of the pointer.
344 void RegisterDataTypeController(
345 sync_driver::DataTypeController* data_type_controller);
347 // Registers a type whose sync storage will not be managed by the
348 // ProfileSyncService. It declares that this sync type may be activated at
349 // some point in the future. This function call does not enable or activate
350 // the syncing of this type
351 void RegisterNonBlockingType(syncer::ModelType type);
353 // Called by a component that supports non-blocking sync when it is ready to
354 // initialize its connection to the sync backend.
356 // If policy allows for syncing this type (ie. it is "preferred"), then this
357 // should result in a message to enable syncing for this type when the sync
358 // backend is available. If the type is not to be synced, this should result
359 // in a message that allows the component to delete its local sync state.
360 void InitializeNonBlockingType(
361 syncer::ModelType type,
362 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
363 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& proxy);
365 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
366 // currently syncing, returns NULL.
367 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
369 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
370 virtual browser_sync::SyncedWindowDelegatesGetter*
371 GetSyncedWindowDelegatesGetter() const;
373 // Returns the SyncableService for syncer::SESSIONS.
374 virtual syncer::SyncableService* GetSessionsSyncableService();
376 // Returns DeviceInfo provider for the local device.
377 virtual browser_sync::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider();
379 // Returns sync's representation of the device info for a client identified
380 // by |client_id|. Return value is an empty scoped ptr if the device info
382 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
383 const std::string& client_id) const;
385 // Gets the device info for all devices signed into the account associated
386 // with this profile.
387 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const;
389 // Notifies the observer of any device info changes.
390 virtual void AddObserverForDeviceInfoChange(
391 browser_sync::SyncedDeviceTracker::Observer* observer);
393 // Removes the observer from device info notification.
394 virtual void RemoveObserverForDeviceInfoChange(
395 browser_sync::SyncedDeviceTracker::Observer* observer);
397 // Fills state_map with a map of current data types that are possible to
398 // sync, as well as their states.
399 void GetDataTypeControllerStates(
400 sync_driver::DataTypeController::StateMap* state_map) const;
402 // Disables sync for user. Use ShowLoginDialog to enable.
403 virtual void DisableForUser();
405 // Disables sync for the user and prevents it from starting on next restart.
406 virtual void StopSyncingPermanently();
408 // SyncFrontend implementation.
409 virtual void OnBackendInitialized(
410 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
411 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
413 const std::string& cache_guid,
414 bool success) OVERRIDE;
415 virtual void OnSyncCycleCompleted() OVERRIDE;
416 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
417 virtual void OnDirectoryTypeCommitCounterUpdated(
418 syncer::ModelType type,
419 const syncer::CommitCounters& counters) OVERRIDE;
420 virtual void OnDirectoryTypeUpdateCounterUpdated(
421 syncer::ModelType type,
422 const syncer::UpdateCounters& counters) OVERRIDE;
423 virtual void OnDirectoryTypeStatusCounterUpdated(
424 syncer::ModelType type,
425 const syncer::StatusCounters& counters) OVERRIDE;
426 virtual void OnSyncConfigureRetry() OVERRIDE;
427 virtual void OnConnectionStatusChange(
428 syncer::ConnectionStatus status) OVERRIDE;
429 virtual void OnPassphraseRequired(
430 syncer::PassphraseRequiredReason reason,
431 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
432 virtual void OnPassphraseAccepted() OVERRIDE;
433 virtual void OnEncryptedTypesChanged(
434 syncer::ModelTypeSet encrypted_types,
435 bool encrypt_everything) OVERRIDE;
436 virtual void OnEncryptionComplete() OVERRIDE;
437 virtual void OnMigrationNeededForTypes(
438 syncer::ModelTypeSet types) OVERRIDE;
439 virtual void OnExperimentsChanged(
440 const syncer::Experiments& experiments) OVERRIDE;
441 virtual void OnActionableError(
442 const syncer::SyncProtocolError& error) OVERRIDE;
444 // DataTypeManagerObserver implementation.
445 virtual void OnConfigureDone(
446 const sync_driver::DataTypeManager::ConfigureResult& result) OVERRIDE;
447 virtual void OnConfigureRetry() OVERRIDE;
448 virtual void OnConfigureStart() OVERRIDE;
450 // DataTypeEncryptionHandler implementation.
451 virtual bool IsPassphraseRequired() const OVERRIDE;
452 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
454 // SigninManagerBase::Observer implementation.
455 virtual void GoogleSigninSucceeded(const std::string& username,
456 const std::string& password) OVERRIDE;
457 virtual void GoogleSignedOut(const std::string& username) OVERRIDE;
459 // Called when a user chooses which data types to sync as part of the sync
460 // setup wizard. |sync_everything| represents whether they chose the
461 // "keep everything synced" option; if true, |chosen_types| will be ignored
462 // and all data types will be synced. |sync_everything| means "sync all
463 // current and future data types."
464 virtual void OnUserChoseDatatypes(bool sync_everything,
465 syncer::ModelTypeSet chosen_types);
467 // Get the sync status code.
468 SyncStatusSummary QuerySyncStatusSummary();
470 // Get a description of the sync status for displaying in the user interface.
471 std::string QuerySyncStatusSummaryString();
473 // Initializes a struct of status indicators with data from the backend.
474 // Returns false if the backend was not available for querying; in that case
475 // the struct will be filled with default data.
476 virtual bool QueryDetailedSyncStatus(
477 browser_sync::SyncBackendHost::Status* result);
479 virtual const GoogleServiceAuthError& GetAuthError() const;
481 // Returns true if initial sync setup is in progress (does not return true
482 // if the user is customizing sync after already completing setup once).
483 // ProfileSyncService uses this to determine if it's OK to start syncing, or
484 // if the user is still setting up the initial sync configuration.
485 virtual bool FirstSetupInProgress() const;
487 // Called by the UI to notify the ProfileSyncService that UI is visible so it
488 // will not start syncing. This tells sync whether it's safe to start
489 // downloading data types yet (we don't start syncing until after sync setup
490 // is complete). The UI calls this as soon as any part of the signin wizard is
491 // displayed (even just the login UI).
492 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
493 // that data download starts.
494 virtual void SetSetupInProgress(bool setup_in_progress);
496 // Returns true if the SyncBackendHost has told us it's ready to accept
498 // [REMARK] - it is safe to call this function only from the ui thread.
499 // because the variable is not thread safe and should only be accessed from
500 // single thread. If we want multiple threads to access this(and there is
501 // currently no need to do so) we need to protect this with a lock.
502 // TODO(timsteele): What happens if the bookmark model is loaded, a change
503 // takes place, and the backend isn't initialized yet?
504 virtual bool sync_initialized() const;
506 virtual bool HasUnrecoverableError() const;
507 const std::string& unrecoverable_error_message() {
508 return unrecoverable_error_message_;
510 tracked_objects::Location unrecoverable_error_location() {
511 return unrecoverable_error_location_;
514 // Returns true if OnPassphraseRequired has been called for decryption and
515 // we have an encrypted data type enabled.
516 virtual bool IsPassphraseRequiredForDecryption() const;
518 syncer::PassphraseRequiredReason passphrase_required_reason() const {
519 return passphrase_required_reason_;
522 // Returns a user-friendly string form of last synced time (in minutes).
523 virtual base::string16 GetLastSyncedTimeString() const;
525 // Returns a human readable string describing backend initialization state.
526 std::string GetBackendInitializationStateString() const;
528 // Returns true if startup is suppressed (i.e. user has stopped syncing via
529 // the google dashboard).
530 virtual bool IsStartSuppressed() const;
532 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
534 // The profile we are syncing for.
535 Profile* profile() const { return profile_; }
537 // Returns a weak pointer to the service's JsController.
538 // Overrideable for testing purposes.
539 virtual base::WeakPtr<syncer::JsController> GetJsController();
541 // Record stats on various events.
542 static void SyncEvent(SyncEventCodes code);
544 // Returns whether sync is enabled. Sync can be enabled/disabled both
545 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
546 // command-line switches).
547 // Profile::IsSyncAccessible() is probably a better signal than this function.
548 // This function can be called from any thread, and the implementation doesn't
549 // assume it's running on the UI thread.
550 static bool IsSyncEnabled();
552 // Returns whether sync is managed, i.e. controlled by configuration
553 // management. If so, the user is not allowed to configure sync.
554 virtual bool IsManaged() const;
556 // syncer::UnrecoverableErrorHandler implementation.
557 virtual void OnUnrecoverableError(
558 const tracked_objects::Location& from_here,
559 const std::string& message) OVERRIDE;
561 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
562 // not change the preferred state of a datatype, and is not persisted across
564 void ReenableDatatype(syncer::ModelType type);
566 // The functions below (until ActivateDataType()) should only be
567 // called if sync_initialized() is true.
569 // TODO(akalin): This is called mostly by ModelAssociators and
570 // tests. Figure out how to pass the handle to the ModelAssociators
571 // directly, figure out how to expose this to tests, and remove this
573 virtual syncer::UserShare* GetUserShare() const;
575 // TODO(akalin): These two functions are used only by
576 // ProfileSyncServiceHarness. Figure out a different way to expose
577 // this info to that class, and remove these functions.
579 virtual syncer::sessions::SyncSessionSnapshot
580 GetLastSessionSnapshot() const;
582 // Returns whether or not the underlying sync engine has made any
583 // local changes to items that have not yet been synced with the
585 bool HasUnsyncedItems() const;
587 // Used by ProfileSyncServiceHarness. May return NULL.
588 browser_sync::BackendMigrator* GetBackendMigratorForTest();
590 // Used by tests to inspect interaction with OAuth2TokenService.
591 bool IsRetryingAccessTokenFetchForTest() const;
593 // Used by tests to inspect the OAuth2 access tokens used by PSS.
594 std::string GetAccessTokenForTest() const;
596 // TODO(sync): This is only used in tests. Can we remove it?
597 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
599 // Returns a ListValue indicating the status of all registered types.
602 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
603 // where <name> is a type's name, <value> is a string providing details for
604 // the type's status, and <status> is one of "error", "warning" or "ok"
605 // depending on the type's current status.
607 // This function is used by about_sync_util.cc to help populate the about:sync
608 // page. It returns a ListValue rather than a DictionaryValue in part to make
609 // it easier to iterate over its elements when constructing that page.
610 base::Value* GetTypeStatusMap() const;
612 // Overridden by tests.
613 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
614 virtual void DeactivateDataType(syncer::ModelType type);
616 // SyncPrefObserver implementation.
617 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
619 // Changes which data types we're going to be syncing to |preferred_types|.
620 // If it is running, the DataTypeManager will be instructed to reconfigure
621 // the sync backend so that exactly these datatypes are actively synced. See
622 // class comment for more on what it means for a datatype to be Preferred.
623 virtual void ChangePreferredDataTypes(
624 syncer::ModelTypeSet preferred_types);
626 // Returns the set of types which are preferred for enabling. This is a
627 // superset of the active types (see GetActiveDataTypes()).
628 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
630 // Returns the set of directory types which are preferred for enabling.
631 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
633 // Returns the set of off-thread types which are preferred for enabling.
634 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
636 // Gets the set of all data types that could be allowed (the set that
637 // should be advertised to the user). These will typically only change
638 // via a command-line option. See class comment for more on what it means
639 // for a datatype to be Registered.
640 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
642 // Gets the set of directory types which could be allowed.
643 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
645 // Gets the set of off-thread types which could be allowed.
646 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
648 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
649 // for sensitive data types. Caller must be holding a
650 // syncapi::BaseTransaction to ensure thread safety.
651 virtual bool IsCryptographerReady(
652 const syncer::BaseTransaction* trans) const;
654 // Returns true if a secondary (explicit) passphrase is being used. It is not
655 // legal to call this method before the backend is initialized.
656 virtual bool IsUsingSecondaryPassphrase() const;
658 // Returns the actual passphrase type being used for encryption.
659 virtual syncer::PassphraseType GetPassphraseType() const;
661 // Returns the time the current explicit passphrase (if any), was set.
662 // If no secondary passphrase is in use, or no time is available, returns an
664 virtual base::Time GetExplicitPassphraseTime() const;
666 // Note about setting passphrases: There are different scenarios under which
667 // we might want to apply a passphrase. It could be for first-time encryption,
668 // re-encryption, or for decryption by clients that sign in at a later time.
669 // In addition, encryption can either be done using a custom passphrase, or by
670 // reusing the GAIA password. Depending on what is happening in the system,
671 // callers should determine which of the two methods below must be used.
673 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
674 // specifies whether the passphrase is a custom passphrase or the GAIA
675 // password being reused as a passphrase.
676 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
677 // passphrase with this API.
678 virtual void SetEncryptionPassphrase(const std::string& passphrase,
679 PassphraseType type);
681 // Asynchronously decrypts pending keys using |passphrase|. Returns false
682 // immediately if the passphrase could not be used to decrypt a locally cached
683 // copy of encrypted keys; returns true otherwise.
684 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
687 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
688 // after calling this to force the encryption to occur.
689 virtual void EnableEncryptEverything();
691 // Returns true if we are currently set to encrypt all the sync data. Note:
692 // this is based on the cryptographer's settings, so if the user has recently
693 // requested encryption to be turned on, this may not be true yet. For that,
694 // encryption_pending() must be checked.
695 virtual bool EncryptEverythingEnabled() const;
697 // Returns true if the syncer is waiting for new datatypes to be encrypted.
698 virtual bool encryption_pending() const;
700 const GURL& sync_service_url() const { return sync_service_url_; }
701 SigninManagerBase* signin() const;
704 bool auto_start_enabled() const;
705 bool setup_in_progress() const;
707 // Stops the sync backend and sets the flag for suppressing sync startup.
708 void StopAndSuppress();
710 // Resets the flag for suppressing sync startup and starts the sync backend.
711 virtual void UnsuppressAndStart();
713 // Marks all currently registered types as "acknowledged" so we won't prompt
714 // the user about them any more.
715 void AcknowledgeSyncedTypes();
717 SyncErrorController* sync_error_controller() {
718 return sync_error_controller_.get();
721 // TODO(sync): This is only used in tests. Can we remove it?
722 const sync_driver::FailedDataTypesHandler& failed_data_types_handler() const;
724 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
725 return configure_status_;
728 // If true, the ProfileSyncService has detected that a new GAIA signin has
729 // succeeded, and is waiting for initialization to complete. This is used by
730 // the UI to differentiate between a new auth error (encountered as part of
731 // the initialization process) and a pre-existing auth error that just hasn't
732 // been cleared yet. Virtual for testing purposes.
733 virtual bool waiting_for_auth() const;
735 // The set of currently enabled sync experiments.
736 const syncer::Experiments& current_experiments() const;
738 // OAuth2TokenService::Consumer implementation.
739 virtual void OnGetTokenSuccess(
740 const OAuth2TokenService::Request* request,
741 const std::string& access_token,
742 const base::Time& expiration_time) OVERRIDE;
743 virtual void OnGetTokenFailure(
744 const OAuth2TokenService::Request* request,
745 const GoogleServiceAuthError& error) OVERRIDE;
747 // OAuth2TokenService::Observer implementation.
748 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
749 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
750 virtual void OnRefreshTokensLoaded() OVERRIDE;
752 // KeyedService implementation. This must be called exactly
753 // once (before this object is destroyed).
754 virtual void Shutdown() OVERRIDE;
756 // Called when a datatype (SyncableService) has a need for sync to start
757 // ASAP, presumably because a local change event has occurred but we're
758 // still in deferred start mode, meaning the SyncableService hasn't been
759 // told to MergeDataAndStartSyncing yet.
760 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
762 // Return sync token status.
763 SyncTokenStatus GetSyncTokenStatus() const;
765 browser_sync::FaviconCache* GetFaviconCache();
767 // Overrides the NetworkResources used for Sync connections.
768 // This function takes ownership of |network_resources|.
769 void OverrideNetworkResourcesForTest(
770 scoped_ptr<syncer::NetworkResources> network_resources);
772 virtual bool IsSessionsDataTypeControllerRunning() const;
774 BackendMode backend_mode() const {
775 return backend_mode_;
778 void SetClearingBrowseringDataForTesting(
779 base::Callback<void(Profile*, base::Time, base::Time)> c);
781 // Return the base URL of the Sync Server.
782 static GURL GetSyncServiceURL(const base::CommandLine& command_line);
784 base::Time GetDeviceBackupTimeForTesting() const;
787 // Helper to configure the priority data types.
788 void ConfigurePriorityDataTypes();
790 // Helper to install and configure a data type manager.
791 void ConfigureDataTypeManager();
793 // Shuts down the backend sync components.
794 // |reason| dictates if syncing is being disabled or not, and whether
795 // to claim ownership of sync thread from backend.
796 void ShutdownImpl(syncer::ShutdownReason reason);
798 // Return SyncCredentials from the OAuth2TokenService.
799 syncer::SyncCredentials GetCredentials();
801 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
803 const sync_driver::DataTypeController::TypeMap&
804 directory_data_type_controllers() {
805 return directory_data_type_controllers_;
808 // Helper method for managing encryption UI.
809 bool IsEncryptedDatatypeEnabled() const;
811 // Helper for OnUnrecoverableError.
812 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
813 // and in SyncBackendHost::Shutdown.
814 void OnUnrecoverableErrorImpl(
815 const tracked_objects::Location& from_here,
816 const std::string& message,
817 bool delete_sync_database);
819 virtual bool NeedBackup() const;
821 // This is a cache of the last authentication response we received from the
822 // sync server. The UI queries this to display appropriate messaging to the
824 GoogleServiceAuthError last_auth_error_;
826 // Our asynchronous backend to communicate with sync components living on
828 scoped_ptr<browser_sync::SyncBackendHost> backend_;
830 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
831 // was required for encryption, decryption with a cached passphrase, or
832 // because a new passphrase is required?
833 syncer::PassphraseRequiredReason passphrase_required_reason_;
836 enum UnrecoverableErrorReason {
839 ERROR_REASON_BACKEND_INIT_FAILURE,
840 ERROR_REASON_CONFIGURATION_RETRY,
841 ERROR_REASON_CONFIGURATION_FAILURE,
842 ERROR_REASON_ACTIONABLE_ERROR,
846 enum AuthErrorMetric {
847 AUTH_ERROR_ENCOUNTERED,
852 friend class ProfileSyncServicePasswordTest;
853 friend class SyncTest;
854 friend class TestProfileSyncService;
855 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
857 // Update the last auth error and notify observers of error state.
858 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
860 // Detects and attempts to recover from a previous improper datatype
861 // configuration where Keep Everything Synced and the preferred types were
862 // not correctly set.
863 void TrySyncDatatypePrefRecovery();
865 // Puts the backend's sync scheduler into NORMAL mode.
866 // Called when configuration is complete.
867 void StartSyncingWithServer();
869 // Called when we've determined that we don't need a passphrase (either
870 // because OnPassphraseAccepted() was called, or because we've gotten a
871 // OnPassphraseRequired() but no data types are enabled).
872 void ResolvePassphraseRequired();
874 // During initial signin, ProfileSyncService caches the user's signin
875 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
876 // This routine is invoked once the backend has started up to use the
877 // cached passphrase and clear it out when it is done.
878 void ConsumeCachedPassphraseIfPossible();
880 // RequestAccessToken initiates RPC to request downscoped access token from
881 // refresh token. This happens when a new OAuth2 login token is loaded and
882 // when sync server returns AUTH_ERROR which indicates it is time to refresh
884 virtual void RequestAccessToken();
886 // Return true if backend should start from a fresh sync DB.
887 bool ShouldDeleteSyncFolder();
889 // If |delete_sync_data_folder| is true, then this method will delete all
890 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
891 void InitializeBackend(bool delete_sync_data_folder);
893 // Initializes the various settings from the command line.
896 // Sets the last synced time to the current time.
897 void UpdateLastSyncedTime();
899 void NotifyObservers();
900 void NotifySyncCycleCompleted();
902 void ClearStaleErrors();
904 void ClearUnrecoverableError();
906 // Starts up the backend sync components. |mode| specifies the kind of
907 // backend to start, one of SYNC, BACKUP or ROLLBACK.
908 virtual void StartUpSlowBackendComponents(BackendMode mode);
910 // About-flags experiment names for datatypes that aren't enabled by default
912 static std::string GetExperimentNameForDataType(
913 syncer::ModelType data_type);
915 // Create and register a new datatype controller.
916 void RegisterNewDataType(syncer::ModelType data_type);
918 // Reconfigures the data type manager with the latest enabled types.
919 // Note: Does not initialize the backend if it is not already initialized.
920 // This function needs to be called only after sync has been initialized
921 // (i.e.,only for reconfigurations). The reason we don't initialize the
922 // backend is because if we had encountered an unrecoverable error we don't
923 // want to startup once more.
924 virtual void ReconfigureDatatypeManager();
926 // Collects preferred sync data types from |preference_providers_|.
927 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
929 // Called when the user changes the sync configuration, to update the UMA
931 void UpdateSelectedTypesHistogram(
932 bool sync_everything,
933 const syncer::ModelTypeSet chosen_types) const;
935 #if defined(OS_CHROMEOS)
936 // Refresh spare sync bootstrap token for re-enabling the sync service.
937 // Called on successful sign-in notifications.
938 void RefreshSpareBootstrapToken(const std::string& passphrase);
941 // Internal unrecoverable error handler. Used to track error reason via
942 // Sync.UnrecoverableErrors histogram.
943 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
944 const std::string& message,
945 bool delete_sync_database,
946 UnrecoverableErrorReason reason);
948 // Returns the type of manager to use according to |backend_mode_|.
949 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
951 // Update UMA for syncing backend.
952 void UpdateBackendInitUMA(bool success);
954 // Various setup following backend initialization, mostly for syncing backend.
955 void PostBackendInitialization();
957 // True if a syncing backend exists.
958 bool HasSyncingBackend() const;
960 // Update first sync time stored in preferences
961 void UpdateFirstSyncTimePref();
963 // Clear browsing data since first sync during rollback.
964 void ClearBrowsingDataSinceFirstSync();
966 // Post background task to check sync backup DB state if needed.
967 void CheckSyncBackupIfNeeded();
969 // Callback to receive backup DB check result.
970 void CheckSyncBackupCallback(base::Time backup_time);
972 // Callback function to call |startup_controller_|.TryStart() after
973 // backup/rollback finishes;
974 void TryStartSyncAfterBackup();
976 // Clean up prefs and backup DB when rollback is not needed.
977 void CleanUpBackup();
979 // Factory used to create various dependent objects.
980 scoped_ptr<ProfileSyncComponentsFactory> factory_;
982 // The profile whose data we are synchronizing.
985 // The class that handles getting, setting, and persisting sync
987 sync_driver::SyncPrefs sync_prefs_;
989 // TODO(ncarter): Put this in a profile, once there is UI for it.
990 // This specifies where to find the sync server.
991 const GURL sync_service_url_;
993 // The last time we detected a successful transition from SYNCING state.
994 // Our backend notifies us whenever we should take a new snapshot.
995 base::Time last_synced_time_;
997 // The time that OnConfigureStart is called. This member is zero if
998 // OnConfigureStart has not yet been called, and is reset to zero once
999 // OnConfigureDone is called.
1000 base::Time sync_configure_start_time_;
1002 // Indicates if this is the first time sync is being configured. This value
1003 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
1004 bool is_first_time_sync_configure_;
1006 // List of available data type controllers for directory types.
1007 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
1009 // Whether the SyncBackendHost has been initialized.
1010 bool backend_initialized_;
1012 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1013 // ProfileSyncService from starting backend till browser restarted or user
1015 bool sync_disabled_by_admin_;
1017 // Set to true if a signin has completed but we're still waiting for the
1018 // backend to refresh its credentials.
1019 bool is_auth_in_progress_;
1021 // Encapsulates user signin - used to set/get the user's authenticated
1023 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
1025 // Information describing an unrecoverable error.
1026 UnrecoverableErrorReason unrecoverable_error_reason_;
1027 std::string unrecoverable_error_message_;
1028 tracked_objects::Location unrecoverable_error_location_;
1030 // Manages the start and stop of the directory data types.
1031 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
1033 // Manager for the non-blocking data types.
1034 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
1036 ObserverList<ProfileSyncServiceBase::Observer> observers_;
1037 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
1038 ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
1040 std::set<SyncTypePreferenceProvider*> preference_providers_;
1042 syncer::SyncJsController sync_js_controller_;
1044 // This allows us to gracefully handle an ABORTED return code from the
1045 // DataTypeManager in the event that the server informed us to cease and
1046 // desist syncing immediately.
1047 bool expect_sync_configuration_aborted_;
1049 // Sometimes we need to temporarily hold on to a passphrase because we don't
1050 // yet have a backend to send it to. This happens during initialization as
1051 // we don't StartUp until we have a valid token, which happens after valid
1052 // credentials were provided.
1053 std::string cached_passphrase_;
1055 // The current set of encrypted types. Always a superset of
1056 // syncer::Cryptographer::SensitiveTypes().
1057 syncer::ModelTypeSet encrypted_types_;
1059 // Whether we want to encrypt everything.
1060 bool encrypt_everything_;
1062 // Whether we're waiting for an attempt to encryption all sync data to
1063 // complete. We track this at this layer in order to allow the user to cancel
1064 // if they e.g. don't remember their explicit passphrase.
1065 bool encryption_pending_;
1067 scoped_ptr<browser_sync::BackendMigrator> migrator_;
1069 // This is the last |SyncProtocolError| we received from the server that had
1070 // an action set on it.
1071 syncer::SyncProtocolError last_actionable_error_;
1073 // Exposes sync errors to the UI.
1074 scoped_ptr<SyncErrorController> sync_error_controller_;
1076 // Tracks the set of failed data types (those that encounter an error
1077 // or must delay loading for some reason).
1078 sync_driver::FailedDataTypesHandler failed_data_types_handler_;
1080 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
1082 // The set of currently enabled sync experiments.
1083 syncer::Experiments current_experiments_;
1085 // Sync's internal debug info listener. Used to record datatype configuration
1086 // and association information.
1087 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1089 // A thread where all the sync operations happen.
1091 // * Created when backend starts for the first time.
1092 // * If sync is disabled, PSS claims ownership from backend.
1093 // * If sync is reenabled, PSS passes ownership to new backend.
1094 scoped_ptr<base::Thread> sync_thread_;
1096 // ProfileSyncService uses this service to get access tokens.
1097 ProfileOAuth2TokenService* const oauth2_token_service_;
1099 // ProfileSyncService needs to remember access token in order to invalidate it
1100 // with OAuth2TokenService.
1101 std::string access_token_;
1103 // ProfileSyncService needs to hold reference to access_token_request_ for
1104 // the duration of request in order to receive callbacks.
1105 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1107 // If RequestAccessToken fails with transient error then retry requesting
1108 // access token with exponential backoff.
1109 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1110 net::BackoffEntry request_access_token_backoff_;
1112 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1114 // We don't use |weak_factory_| for the StartupController because the weak
1115 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1116 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1117 // StartupController an Unretained reference to future-proof against
1118 // the controller impl changing to post tasks. Therefore, we have a separate
1120 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1122 // States related to sync token and connection.
1123 base::Time connection_status_update_time_;
1124 syncer::ConnectionStatus connection_status_;
1125 base::Time token_request_time_;
1126 base::Time token_receive_time_;
1127 GoogleServiceAuthError last_get_token_error_;
1128 base::Time next_token_request_time_;
1130 scoped_ptr<LocalDeviceInfoProvider> local_device_;
1132 // Locally owned SyncableService implementations.
1133 scoped_ptr<SessionsSyncManager> sessions_sync_manager_;
1135 scoped_ptr<syncer::NetworkResources> network_resources_;
1137 browser_sync::StartupController startup_controller_;
1139 browser_sync::BackupRollbackController backup_rollback_controller_;
1141 // Mode of current backend.
1142 BackendMode backend_mode_;
1144 // Whether backup is needed before sync starts.
1147 // Whether backup is finished.
1148 bool backup_finished_;
1150 base::Time backup_start_time_;
1152 base::Callback<void(Profile*, base::Time, base::Time)> clear_browsing_data_;
1154 // Last time when pre-sync data was saved. NULL pointer means backup data
1155 // state is unknown. If time value is null, backup data doesn't exist.
1156 scoped_ptr<base::Time> last_backup_time_;
1158 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1161 bool ShouldShowActionOnUI(
1162 const syncer::SyncProtocolError& error);
1165 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_