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/signin/signin_global_error.h"
24 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
25 #include "chrome/browser/sync/glue/data_type_controller.h"
26 #include "chrome/browser/sync/glue/data_type_encryption_handler.h"
27 #include "chrome/browser/sync/glue/data_type_manager.h"
28 #include "chrome/browser/sync/glue/data_type_manager_observer.h"
29 #include "chrome/browser/sync/glue/failed_data_types_handler.h"
30 #include "chrome/browser/sync/glue/sync_backend_host.h"
31 #include "chrome/browser/sync/glue/synced_device_tracker.h"
32 #include "chrome/browser/sync/profile_sync_service_base.h"
33 #include "chrome/browser/sync/profile_sync_service_observer.h"
34 #include "chrome/browser/sync/sync_prefs.h"
35 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
36 #include "content/public/browser/notification_observer.h"
37 #include "content/public/browser/notification_registrar.h"
38 #include "content/public/browser/notification_types.h"
39 #include "google_apis/gaia/google_service_auth_error.h"
40 #include "google_apis/gaia/oauth2_token_service.h"
41 #include "net/base/backoff_entry.h"
42 #include "sync/internal_api/public/base/model_type.h"
43 #include "sync/internal_api/public/engine/model_safe_worker.h"
44 #include "sync/internal_api/public/sync_manager_factory.h"
45 #include "sync/internal_api/public/util/experiments.h"
46 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
47 #include "sync/js/sync_js_controller.h"
50 class ProfileOAuth2TokenService;
52 class ProfileSyncComponentsFactory;
53 class SigninManagerBase;
54 class SyncGlobalError;
56 namespace browser_sync {
57 class BackendMigrator;
58 class ChangeProcessor;
59 class DataTypeManager;
62 class SessionModelAssociator;
65 class SyncSessionSnapshot;
66 } // namespace sessions
67 } // namespace browser_sync
70 class BaseTransaction;
71 struct SyncCredentials;
77 } // namespace sync_pb
79 // ProfileSyncService is the layer between browser subsystems like bookmarks,
80 // and the sync backend. Each subsystem is logically thought of as being
83 // Individual datatypes can, at any point, be in a variety of stages of being
84 // "enabled". Here are some specific terms for concepts used in this class:
86 // 'Registered' (feature suppression for a datatype)
88 // When a datatype is registered, the user has the option of syncing it.
89 // The sync opt-in UI will show only registered types; a checkbox should
90 // never be shown for an unregistered type, and nor should it ever be
93 // A datatype is considered registered once RegisterDataTypeController
94 // has been called with that datatype's DataTypeController.
96 // 'Preferred' (user preferences and opt-out for a datatype)
98 // This means the user's opt-in or opt-out preference on a per-datatype
99 // basis. The sync service will try to make active exactly these types.
100 // If a user has opted out of syncing a particular datatype, it will
101 // be registered, but not preferred.
103 // This state is controlled by the ConfigurePreferredDataTypes and
104 // GetPreferredDataTypes. They are stored in the preferences system,
105 // and persist; though if a datatype is not registered, it cannot
106 // be a preferred datatype.
108 // 'Active' (run-time initialization of sync system for a datatype)
110 // An active datatype is a preferred datatype that is actively being
111 // synchronized: the syncer has been instructed to querying the server
112 // for this datatype, first-time merges have finished, and there is an
113 // actively installed ChangeProcessor that listens for changes to this
114 // datatype, propagating such changes into and out of the sync backend
117 // When a datatype is in the process of becoming active, it may be
118 // in some intermediate state. Those finer-grained intermediate states
119 // are differentiated by the DataTypeController state.
121 // Sync Configuration:
123 // Sync configuration is accomplished via the following APIs:
124 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
125 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
126 // using the passed passphrase.
127 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
130 // Additionally, the current sync configuration can be fetched by calling
131 // * GetRegisteredDataTypes()
132 // * GetPreferredDataTypes()
133 // * GetActiveDataTypes()
134 // * IsUsingSecondaryPassphrase()
135 // * EncryptEverythingEnabled()
136 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
138 // The "sync everything" state cannot be read from ProfileSyncService, but
139 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
141 // Initial sync setup:
143 // For privacy reasons, it is usually desirable to avoid syncing any data
144 // types until the user has finished setting up sync. There are two APIs
145 // that control the initial sync download:
147 // * SetSyncSetupCompleted()
148 // * SetSetupInProgress()
150 // SetSyncSetupCompleted() should be called once the user has finished setting
151 // up sync at least once on their account. SetSetupInProgress(true) should be
152 // called while the user is actively configuring their account, and then
153 // SetSetupInProgress(false) should be called when configuration is complete.
154 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
155 // been called, then the sync engine knows not to download any user data.
157 // When initial sync is complete, the UI code should call
158 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
159 // tell the sync engine that setup is completed and it can begin downloading
160 // data from the sync server.
162 class ProfileSyncService : public ProfileSyncServiceBase,
163 public browser_sync::SyncFrontend,
164 public browser_sync::SyncPrefObserver,
165 public browser_sync::DataTypeManagerObserver,
166 public SigninGlobalError::AuthStatusProvider,
167 public syncer::UnrecoverableErrorHandler,
168 public content::NotificationObserver,
169 public BrowserContextKeyedService,
170 public browser_sync::DataTypeEncryptionHandler,
171 public OAuth2TokenService::Consumer,
172 public OAuth2TokenService::Observer {
174 typedef browser_sync::SyncBackendHost::Status Status;
176 enum SyncEventCodes {
177 MIN_SYNC_EVENT_CODE = 0,
179 // Events starting the sync service.
180 START_FROM_NTP = 1, // Sync was started from the ad in NTP
181 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
182 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
183 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
184 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
185 START_FROM_URL = 6, // Sync was started from a typed URL.
187 // Events regarding cancellation of the signon process of sync.
188 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
189 // username and password.
190 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
191 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
192 // types and clicking OK.
193 // Events resulting in the stoppage of sync service.
194 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
195 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
197 // Miscellaneous events caused by sync service.
202 // Defines the type of behavior the sync engine should use. If configured for
203 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted()
204 // and start downloading data types as soon as sync credentials are available
205 // (a signed-in username and a "chromiumsync" token).
206 // If configured for MANUAL_START, sync will not start until the user
207 // completes sync setup, at which point the UI makes an explicit call to
208 // SetSyncSetupCompleted().
214 // Used to specify the kind of passphrase with which sync data is encrypted.
215 enum PassphraseType {
216 IMPLICIT, // The user did not provide a custom passphrase for encryption.
217 // We implicitly use the GAIA password in such cases.
218 EXPLICIT, // The user selected the "use custom passphrase" radio button
219 // during sync setup and provided a passphrase.
222 enum SyncStatusSummary {
226 DATATYPES_NOT_INITIALIZED,
231 // Default sync server URL.
232 static const char* kSyncServerUrl;
233 // Sync server URL for dev channel users
234 static const char* kDevServerUrl;
236 // Takes ownership of |factory|.
237 ProfileSyncService(ProfileSyncComponentsFactory* factory,
239 SigninManagerBase* signin,
240 ProfileOAuth2TokenService* oauth2_token_service,
241 StartBehavior start_behavior);
242 virtual ~ProfileSyncService();
244 // Initializes the object. This must be called at most once, and
245 // immediately after an object of this class is constructed.
248 virtual void SetSyncSetupCompleted();
250 // ProfileSyncServiceBase implementation.
251 virtual bool HasSyncSetupCompleted() const OVERRIDE;
252 virtual bool ShouldPushChanges() OVERRIDE;
253 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
254 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
255 virtual void RemoveObserver(
256 ProfileSyncServiceBase::Observer* observer) OVERRIDE;
257 virtual bool HasObserver(
258 ProfileSyncServiceBase::Observer* observer) const OVERRIDE;
260 void RegisterAuthNotifications();
261 void UnregisterAuthNotifications();
263 // Returns true if sync is enabled/not suppressed and the user is logged in.
264 // (being logged in does not mean that tokens are available - tokens may
265 // be missing because they have not loaded yet, or because they were deleted
266 // due to http://crbug.com/121755).
267 // Virtual to enable mocking in tests.
268 virtual bool IsSyncEnabledAndLoggedIn();
270 // Return whether OAuth2 refresh token is loaded and available for the backend
271 // to start up. Virtual to enable mocking in tests.
272 virtual bool IsOAuthRefreshTokenAvailable();
274 // Registers a data type controller with the sync service. This
275 // makes the data type controller available for use, it does not
276 // enable or activate the synchronization of the data type (see
277 // ActivateDataType). Takes ownership of the pointer.
278 void RegisterDataTypeController(
279 browser_sync::DataTypeController* data_type_controller);
281 // Returns the session model associator associated with this type, but only if
282 // the associator is running. If it is doing anything else, it will return
284 // TODO(zea): Figure out a better way to expose this to the UI elements that
286 virtual browser_sync::SessionModelAssociator* GetSessionModelAssociator();
288 // Returns sync's representation of the local device info.
289 // Return value is an empty scoped_ptr if the device info is unavailable.
290 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo() const;
292 // Returns sync's representation of the device info for a client identified
293 // by |client_id|. Return value is an empty scoped ptr if the device info
295 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
296 const std::string& client_id) const;
298 // Gets the device info for all devices signed into the account associated
299 // with this profile.
300 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const;
302 // Gets the partnership guid for the local device. Can be used by other
303 // layers to distinguish sync data that belongs to the local device vs
304 // data that belong to remote devices. Returns null if sync is not
306 virtual std::string GetLocalDeviceGUID() const;
308 // Notifies the observer of any device info changes.
309 virtual void AddObserverForDeviceInfoChange(
310 browser_sync::SyncedDeviceTracker::Observer* observer);
312 // Removes the observer from device info notification.
313 virtual void RemoveObserverForDeviceInfoChange(
314 browser_sync::SyncedDeviceTracker::Observer* observer);
316 // Fills state_map with a map of current data types that are possible to
317 // sync, as well as their states.
318 void GetDataTypeControllerStates(
319 browser_sync::DataTypeController::StateMap* state_map) const;
321 // Disables sync for user. Use ShowLoginDialog to enable.
322 virtual void DisableForUser();
324 // SyncFrontend implementation.
325 virtual void OnBackendInitialized(
326 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
327 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
329 bool success) OVERRIDE;
330 virtual void OnSyncCycleCompleted() OVERRIDE;
331 virtual void OnSyncConfigureRetry() OVERRIDE;
332 virtual void OnConnectionStatusChange(
333 syncer::ConnectionStatus status) OVERRIDE;
334 virtual void OnStopSyncingPermanently() OVERRIDE;
335 virtual void OnPassphraseRequired(
336 syncer::PassphraseRequiredReason reason,
337 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
338 virtual void OnPassphraseAccepted() OVERRIDE;
339 virtual void OnEncryptedTypesChanged(
340 syncer::ModelTypeSet encrypted_types,
341 bool encrypt_everything) OVERRIDE;
342 virtual void OnEncryptionComplete() OVERRIDE;
343 virtual void OnMigrationNeededForTypes(
344 syncer::ModelTypeSet types) OVERRIDE;
345 virtual void OnExperimentsChanged(
346 const syncer::Experiments& experiments) OVERRIDE;
347 virtual void OnActionableError(
348 const syncer::SyncProtocolError& error) OVERRIDE;
350 // DataTypeManagerObserver implementation.
351 virtual void OnConfigureDone(
352 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE;
353 virtual void OnConfigureRetry() OVERRIDE;
354 virtual void OnConfigureStart() OVERRIDE;
356 // DataTypeEncryptionHandler implementation.
357 virtual bool IsPassphraseRequired() const OVERRIDE;
358 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
360 // Called when a user chooses which data types to sync as part of the sync
361 // setup wizard. |sync_everything| represents whether they chose the
362 // "keep everything synced" option; if true, |chosen_types| will be ignored
363 // and all data types will be synced. |sync_everything| means "sync all
364 // current and future data types."
365 virtual void OnUserChoseDatatypes(bool sync_everything,
366 syncer::ModelTypeSet chosen_types);
368 // Get the sync status code.
369 SyncStatusSummary QuerySyncStatusSummary();
371 // Get a description of the sync status for displaying in the user interface.
372 std::string QuerySyncStatusSummaryString();
374 // Initializes a struct of status indicators with data from the backend.
375 // Returns false if the backend was not available for querying; in that case
376 // the struct will be filled with default data.
377 virtual bool QueryDetailedSyncStatus(
378 browser_sync::SyncBackendHost::Status* result);
380 virtual const GoogleServiceAuthError& GetAuthError() const;
382 // Returns true if initial sync setup is in progress (does not return true
383 // if the user is customizing sync after already completing setup once).
384 // ProfileSyncService uses this to determine if it's OK to start syncing, or
385 // if the user is still setting up the initial sync configuration.
386 virtual bool FirstSetupInProgress() const;
388 // Called by the UI to notify the ProfileSyncService that UI is visible so it
389 // will not start syncing. This tells sync whether it's safe to start
390 // downloading data types yet (we don't start syncing until after sync setup
391 // is complete). The UI calls this as soon as any part of the signin wizard is
392 // displayed (even just the login UI).
393 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
394 // that data download starts.
395 virtual void SetSetupInProgress(bool setup_in_progress);
397 // Returns true if the SyncBackendHost has told us it's ready to accept
399 // [REMARK] - it is safe to call this function only from the ui thread.
400 // because the variable is not thread safe and should only be accessed from
401 // single thread. If we want multiple threads to access this(and there is
402 // currently no need to do so) we need to protect this with a lock.
403 // TODO(timsteele): What happens if the bookmark model is loaded, a change
404 // takes place, and the backend isn't initialized yet?
405 virtual bool sync_initialized() const;
407 virtual bool HasUnrecoverableError() const;
408 const std::string& unrecoverable_error_message() {
409 return unrecoverable_error_message_;
411 tracked_objects::Location unrecoverable_error_location() {
412 return unrecoverable_error_location_;
415 // Returns true if OnPassphraseRequired has been called for decryption and
416 // we have an encrypted data type enabled.
417 virtual bool IsPassphraseRequiredForDecryption() const;
419 syncer::PassphraseRequiredReason passphrase_required_reason() const {
420 return passphrase_required_reason_;
423 // Returns a user-friendly string form of last synced time (in minutes).
424 virtual string16 GetLastSyncedTimeString() const;
426 // Returns a human readable string describing backend initialization state.
427 std::string GetBackendInitializationStateString() const;
429 // Returns true if startup is suppressed (i.e. user has stopped syncing via
430 // the google dashboard).
431 virtual bool IsStartSuppressed() const;
433 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
435 // The profile we are syncing for.
436 Profile* profile() const { return profile_; }
438 // Returns a weak pointer to the service's JsController.
439 // Overrideable for testing purposes.
440 virtual base::WeakPtr<syncer::JsController> GetJsController();
442 // Record stats on various events.
443 static void SyncEvent(SyncEventCodes code);
445 // Returns whether sync is enabled. Sync can be enabled/disabled both
446 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
447 // command-line switches).
448 // Profile::IsSyncAccessible() is probably a better signal than this function.
449 // This function can be called from any thread, and the implementation doesn't
450 // assume it's running on the UI thread.
451 static bool IsSyncEnabled();
453 // Returns whether sync is managed, i.e. controlled by configuration
454 // management. If so, the user is not allowed to configure sync.
455 virtual bool IsManaged() const;
457 // SigninGlobalError::AuthStatusProvider implementation.
458 virtual std::string GetAccountId() const OVERRIDE;
459 virtual GoogleServiceAuthError GetAuthStatus() const OVERRIDE;
461 // syncer::UnrecoverableErrorHandler implementation.
462 virtual void OnUnrecoverableError(
463 const tracked_objects::Location& from_here,
464 const std::string& message) OVERRIDE;
466 // Called when a datatype wishes to disable itself due to having hit an
467 // unrecoverable error.
468 virtual void DisableBrokenDatatype(
469 syncer::ModelType type,
470 const tracked_objects::Location& from_here,
471 std::string message);
473 // The functions below (until ActivateDataType()) should only be
474 // called if sync_initialized() is true.
476 // TODO(akalin): This is called mostly by ModelAssociators and
477 // tests. Figure out how to pass the handle to the ModelAssociators
478 // directly, figure out how to expose this to tests, and remove this
480 virtual syncer::UserShare* GetUserShare() const;
482 // TODO(akalin): These two functions are used only by
483 // ProfileSyncServiceHarness. Figure out a different way to expose
484 // this info to that class, and remove these functions.
486 virtual syncer::sessions::SyncSessionSnapshot
487 GetLastSessionSnapshot() const;
489 // Returns whether or not the underlying sync engine has made any
490 // local changes to items that have not yet been synced with the
492 bool HasUnsyncedItems() const;
494 // Used by ProfileSyncServiceHarness. May return NULL.
495 browser_sync::BackendMigrator* GetBackendMigratorForTest();
497 // TODO(sync): This is only used in tests. Can we remove it?
498 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
500 // Returns a ListValue indicating the status of all registered types.
503 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
504 // where <name> is a type's name, <value> is a string providing details for
505 // the type's status, and <status> is one of "error", "warning" or "ok"
506 // dpending on the type's current status.
508 // This function is used by sync_ui_util.cc to help populate the about:sync
509 // page. It returns a ListValue rather than a DictionaryValue in part to make
510 // it easier to iterate over its elements when constructing that page.
511 Value* GetTypeStatusMap() const;
513 // Overridden by tests.
514 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
515 virtual void ActivateDataType(
516 syncer::ModelType type, syncer::ModelSafeGroup group,
517 browser_sync::ChangeProcessor* change_processor);
518 virtual void DeactivateDataType(syncer::ModelType type);
520 // SyncPrefObserver implementation.
521 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
523 // content::NotificationObserver implementation.
524 virtual void Observe(int type,
525 const content::NotificationSource& source,
526 const content::NotificationDetails& details) OVERRIDE;
528 // Changes which data types we're going to be syncing to |preferred_types|.
529 // If it is running, the DataTypeManager will be instructed to reconfigure
530 // the sync backend so that exactly these datatypes are actively synced. See
531 // class comment for more on what it means for a datatype to be Preferred.
532 virtual void ChangePreferredDataTypes(
533 syncer::ModelTypeSet preferred_types);
535 // Returns the set of types which are preferred for enabling. This is a
536 // superset of the active types (see GetActiveTypes()).
537 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
539 // Gets the set of all data types that could be allowed (the set that
540 // should be advertised to the user). These will typically only change
541 // via a command-line option. See class comment for more on what it means
542 // for a datatype to be Registered.
543 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
545 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
546 // for sensitive data types. Caller must be holding a
547 // syncapi::BaseTransaction to ensure thread safety.
548 virtual bool IsCryptographerReady(
549 const syncer::BaseTransaction* trans) const;
551 // Returns true if a secondary (explicit) passphrase is being used. It is not
552 // legal to call this method before the backend is initialized.
553 virtual bool IsUsingSecondaryPassphrase() const;
555 // Returns the actual passphrase type being used for encryption.
556 virtual syncer::PassphraseType GetPassphraseType() const;
558 // Returns the time the current explicit passphrase (if any), was set.
559 // If no secondary passphrase is in use, or no time is available, returns an
561 virtual base::Time GetExplicitPassphraseTime() const;
563 // Note about setting passphrases: There are different scenarios under which
564 // we might want to apply a passphrase. It could be for first-time encryption,
565 // re-encryption, or for decryption by clients that sign in at a later time.
566 // In addition, encryption can either be done using a custom passphrase, or by
567 // reusing the GAIA password. Depending on what is happening in the system,
568 // callers should determine which of the two methods below must be used.
570 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
571 // specifies whether the passphrase is a custom passphrase or the GAIA
572 // password being reused as a passphrase.
573 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
574 // passphrase with this API.
575 virtual void SetEncryptionPassphrase(const std::string& passphrase,
576 PassphraseType type);
578 // Asynchronously decrypts pending keys using |passphrase|. Returns false
579 // immediately if the passphrase could not be used to decrypt a locally cached
580 // copy of encrypted keys; returns true otherwise.
581 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
584 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
585 // after calling this to force the encryption to occur.
586 virtual void EnableEncryptEverything();
588 // Returns true if we are currently set to encrypt all the sync data. Note:
589 // this is based on the cryptographer's settings, so if the user has recently
590 // requested encryption to be turned on, this may not be true yet. For that,
591 // encryption_pending() must be checked.
592 virtual bool EncryptEverythingEnabled() const;
594 // Returns true if the syncer is waiting for new datatypes to be encrypted.
595 virtual bool encryption_pending() const;
597 const GURL& sync_service_url() const { return sync_service_url_; }
598 bool auto_start_enabled() const { return auto_start_enabled_; }
599 SigninManagerBase* signin() const { return signin_; }
600 bool setup_in_progress() const { return setup_in_progress_; }
602 // Stops the sync backend and sets the flag for suppressing sync startup.
603 void StopAndSuppress();
605 // Resets the flag for suppressing sync startup and starts the sync backend.
606 virtual void UnsuppressAndStart();
608 // Marks all currently registered types as "acknowledged" so we won't prompt
609 // the user about them any more.
610 void AcknowledgeSyncedTypes();
612 SyncGlobalError* sync_global_error() { return sync_global_error_.get(); }
614 // TODO(sync): This is only used in tests. Can we remove it?
615 const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const;
617 browser_sync::DataTypeManager::ConfigureStatus configure_status() {
618 return configure_status_;
621 // If true, the ProfileSyncService has detected that a new GAIA signin has
622 // succeeded, and is waiting for initialization to complete. This is used by
623 // the UI to differentiate between a new auth error (encountered as part of
624 // the initialization process) and a pre-existing auth error that just hasn't
625 // been cleared yet. Virtual for testing purposes.
626 virtual bool waiting_for_auth() const;
628 // The set of currently enabled sync experiments.
629 const syncer::Experiments& current_experiments() const;
631 // OAuth2TokenService::Consumer implementation.
632 virtual void OnGetTokenSuccess(
633 const OAuth2TokenService::Request* request,
634 const std::string& access_token,
635 const base::Time& expiration_time) OVERRIDE;
636 virtual void OnGetTokenFailure(
637 const OAuth2TokenService::Request* request,
638 const GoogleServiceAuthError& error) OVERRIDE;
640 // OAuth2TokenService::Observer implementation.
641 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
642 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
643 virtual void OnRefreshTokensLoaded() OVERRIDE;
645 // BrowserContextKeyedService implementation. This must be called exactly
646 // once (before this object is destroyed).
647 virtual void Shutdown() OVERRIDE;
649 // Called when a datatype (SyncableService) has a need for sync to start
650 // ASAP, presumably because a local change event has occurred but we're
651 // still in deferred start mode, meaning the SyncableService hasn't been
652 // told to MergeDataAndStartSyncing yet.
653 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
656 // Used by test classes that derive from ProfileSyncService.
657 virtual browser_sync::SyncBackendHost* GetBackendForTest();
659 // Helper to configure the priority data types.
660 void ConfigurePriorityDataTypes();
662 // Helper to install and configure a data type manager.
663 void ConfigureDataTypeManager();
665 // Shuts down the backend sync components.
666 // |option| indicates if syncing is being disabled or not, and whether
667 // to claim ownership of sync thread from backend.
668 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option);
670 // Return SyncCredentials from the TokenService.
671 syncer::SyncCredentials GetCredentials();
673 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
675 // Test need to override this to create backends that allow setting up
676 // initial conditions, such as populating sync nodes.
678 // TODO(akalin): Figure out a better way to do this. Ideally, we'd
679 // construct the backend outside this class and pass it in to the
680 // contructor or Initialize().
681 virtual void CreateBackend();
683 const browser_sync::DataTypeController::TypeMap& data_type_controllers() {
684 return data_type_controllers_;
687 // Helper method for managing encryption UI.
688 bool IsEncryptedDatatypeEnabled() const;
690 // Helper for OnUnrecoverableError.
691 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
692 // and in SyncBackendHost::Shutdown.
693 void OnUnrecoverableErrorImpl(
694 const tracked_objects::Location& from_here,
695 const std::string& message,
696 bool delete_sync_database);
698 // This is a cache of the last authentication response we received from the
699 // sync server. The UI queries this to display appropriate messaging to the
701 GoogleServiceAuthError last_auth_error_;
703 // Our asynchronous backend to communicate with sync components living on
705 scoped_ptr<browser_sync::SyncBackendHost> backend_;
707 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
708 // was required for encryption, decryption with a cached passphrase, or
709 // because a new passphrase is required?
710 syncer::PassphraseRequiredReason passphrase_required_reason_;
713 enum UnrecoverableErrorReason {
716 ERROR_REASON_BACKEND_INIT_FAILURE,
717 ERROR_REASON_CONFIGURATION_RETRY,
718 ERROR_REASON_CONFIGURATION_FAILURE,
719 ERROR_REASON_ACTIONABLE_ERROR,
722 friend class ProfileSyncServicePasswordTest;
723 friend class SyncTest;
724 friend class TestProfileSyncService;
725 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
727 // Update the last auth error and notify observers of error state.
728 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
730 // Detects and attempts to recover from a previous improper datatype
731 // configuration where Keep Everything Synced and the preferred types were
732 // not correctly set.
733 void TrySyncDatatypePrefRecovery();
735 // Starts up sync if it is not suppressed and preconditions are met.
736 // Called from Initialize() and UnsuppressAndStart().
739 // Puts the backend's sync scheduler into NORMAL mode.
740 // Called when configuration is complete.
741 void StartSyncingWithServer();
743 // Called when we've determined that we don't need a passphrase (either
744 // because OnPassphraseAccepted() was called, or because we've gotten a
745 // OnPassphraseRequired() but no data types are enabled).
746 void ResolvePassphraseRequired();
748 // During initial signin, ProfileSyncService caches the user's signin
749 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
750 // This routine is invoked once the backend has started up to use the
751 // cached passphrase and clear it out when it is done.
752 void ConsumeCachedPassphraseIfPossible();
754 // RequestAccessToken initiates RPC to request downscoped access token from
755 // refresh token. This happens when TokenService loads OAuth2 login token and
756 // when sync server returns AUTH_ERROR which indicates it is time to refresh
758 virtual void RequestAccessToken();
760 // If |delete_sync_data_folder| is true, then this method will delete all
761 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
762 void InitializeBackend(bool delete_sync_data_folder);
764 // Initializes the various settings from the command line.
767 // Sets the last synced time to the current time.
768 void UpdateLastSyncedTime();
770 void NotifyObservers();
771 void NotifySyncCycleCompleted();
773 void ClearStaleErrors();
775 void ClearUnrecoverableError();
777 enum StartUpDeferredOption {
778 STARTUP_BACKEND_DEFERRED,
781 void StartUp(StartUpDeferredOption deferred_option);
783 // Starts up the backend sync components.
784 void StartUpSlowBackendComponents();
786 // About-flags experiment names for datatypes that aren't enabled by default
788 static std::string GetExperimentNameForDataType(
789 syncer::ModelType data_type);
791 // Create and register a new datatype controller.
792 void RegisterNewDataType(syncer::ModelType data_type);
794 // Reconfigures the data type manager with the latest enabled types.
795 // Note: Does not initialize the backend if it is not already initialized.
796 // This function needs to be called only after sync has been initialized
797 // (i.e.,only for reconfigurations). The reason we don't initialize the
798 // backend is because if we had encountered an unrecoverable error we don't
799 // want to startup once more.
800 virtual void ReconfigureDatatypeManager();
802 // Called when the user changes the sync configuration, to update the UMA
804 void UpdateSelectedTypesHistogram(
805 bool sync_everything,
806 const syncer::ModelTypeSet chosen_types) const;
808 #if defined(OS_CHROMEOS)
809 // Refresh spare sync bootstrap token for re-enabling the sync service.
810 // Called on successful sign-in notifications.
811 void RefreshSpareBootstrapToken(const std::string& passphrase);
814 // Internal unrecoverable error handler. Used to track error reason via
815 // Sync.UnrecoverableErrors histogram.
816 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
817 const std::string& message,
818 bool delete_sync_database,
819 UnrecoverableErrorReason reason);
821 // Returns the username (in form of an email address) that should be used in
823 std::string GetEffectiveUsername();
825 // Factory used to create various dependent objects.
826 scoped_ptr<ProfileSyncComponentsFactory> factory_;
828 // The profile whose data we are synchronizing.
831 // The class that handles getting, setting, and persisting sync
833 browser_sync::SyncPrefs sync_prefs_;
835 // TODO(ncarter): Put this in a profile, once there is UI for it.
836 // This specifies where to find the sync server.
837 GURL sync_service_url_;
839 // The last time we detected a successful transition from SYNCING state.
840 // Our backend notifies us whenever we should take a new snapshot.
841 base::Time last_synced_time_;
843 // The time that StartUp() is called. This member is zero if StartUp() has
844 // never been called, and is reset to zero once OnBackendInitialized() is
846 base::Time start_up_time_;
848 // Whether we have received a signal from a SyncableService requesting that
849 // sync starts as soon as possible.
850 // TODO(tim): Move this and other TryStart related logic + state to separate
852 bool data_type_requested_sync_startup_;
854 // The time that OnConfigureStart is called. This member is zero if
855 // OnConfigureStart has not yet been called, and is reset to zero once
856 // OnConfigureDone is called.
857 base::Time sync_configure_start_time_;
859 // Indicates if this is the first time sync is being configured. This value
860 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
861 bool is_first_time_sync_configure_;
863 // List of available data type controllers.
864 browser_sync::DataTypeController::TypeMap data_type_controllers_;
866 // Whether the SyncBackendHost has been initialized.
867 bool backend_initialized_;
869 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
870 // ProfileSyncService from starting backend till browser restarted or user
872 bool sync_disabled_by_admin_;
874 // Set to true if a signin has completed but we're still waiting for the
875 // backend to refresh its credentials.
876 bool is_auth_in_progress_;
878 // Encapsulates user signin - used to set/get the user's authenticated
880 SigninManagerBase* signin_;
882 // Information describing an unrecoverable error.
883 UnrecoverableErrorReason unrecoverable_error_reason_;
884 std::string unrecoverable_error_message_;
885 tracked_objects::Location unrecoverable_error_location_;
887 // Manages the start and stop of the various data types.
888 scoped_ptr<browser_sync::DataTypeManager> data_type_manager_;
890 ObserverList<ProfileSyncServiceBase::Observer> observers_;
892 syncer::SyncJsController sync_js_controller_;
894 content::NotificationRegistrar registrar_;
896 // This allows us to gracefully handle an ABORTED return code from the
897 // DataTypeManager in the event that the server informed us to cease and
898 // desist syncing immediately.
899 bool expect_sync_configuration_aborted_;
901 // Sometimes we need to temporarily hold on to a passphrase because we don't
902 // yet have a backend to send it to. This happens during initialization as
903 // we don't StartUp until we have a valid token, which happens after valid
904 // credentials were provided.
905 std::string cached_passphrase_;
907 // The current set of encrypted types. Always a superset of
908 // syncer::Cryptographer::SensitiveTypes().
909 syncer::ModelTypeSet encrypted_types_;
911 // Whether we want to encrypt everything.
912 bool encrypt_everything_;
914 // Whether we're waiting for an attempt to encryption all sync data to
915 // complete. We track this at this layer in order to allow the user to cancel
916 // if they e.g. don't remember their explicit passphrase.
917 bool encryption_pending_;
919 // If true, we want to automatically start sync signin whenever we have
920 // credentials (user doesn't need to go through the startup flow). This is
921 // typically enabled on platforms (like ChromeOS) that have their own
922 // distinct signin flow.
923 const bool auto_start_enabled_;
925 scoped_ptr<browser_sync::BackendMigrator> migrator_;
927 // This is the last |SyncProtocolError| we received from the server that had
928 // an action set on it.
929 syncer::SyncProtocolError last_actionable_error_;
931 // This is used to show sync errors in the wrench menu.
932 scoped_ptr<SyncGlobalError> sync_global_error_;
934 // Tracks the set of failed data types (those that encounter an error
935 // or must delay loading for some reason).
936 browser_sync::FailedDataTypesHandler failed_data_types_handler_;
938 browser_sync::DataTypeManager::ConfigureStatus configure_status_;
940 // If |true|, there is setup UI visible so we should not start downloading
942 bool setup_in_progress_;
944 // The set of currently enabled sync experiments.
945 syncer::Experiments current_experiments_;
947 // Sync's internal debug info listener. Used to record datatype configuration
948 // and association information.
949 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
951 // A thread where all the sync operations happen.
953 // * Created when backend starts for the first time.
954 // * If sync is disabled, PSS claims ownership from backend.
955 // * If sync is reenabled, PSS passes ownership to new backend.
956 scoped_ptr<base::Thread> sync_thread_;
958 // ProfileSyncService uses this service to get access tokens.
959 ProfileOAuth2TokenService* oauth2_token_service_;
961 // ProfileSyncService needs to remember access token in order to invalidate it
962 // with OAuth2TokenService.
963 std::string access_token_;
965 // ProfileSyncService needs to hold reference to access_token_request_ for
966 // the duration of request in order to receive callbacks.
967 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
969 // If RequestAccessToken fails with transient error then retry requesting
970 // access token with exponential backoff.
971 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
972 net::BackoffEntry request_access_token_backoff_;
974 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
976 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
979 bool ShouldShowActionOnUI(
980 const syncer::SyncProtocolError& error);
983 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_