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/glue/data_type_controller.h"
25 #include "chrome/browser/sync/glue/data_type_encryption_handler.h"
26 #include "chrome/browser/sync/glue/data_type_manager.h"
27 #include "chrome/browser/sync/glue/data_type_manager_observer.h"
28 #include "chrome/browser/sync/glue/failed_data_types_handler.h"
29 #include "chrome/browser/sync/glue/sync_backend_host.h"
30 #include "chrome/browser/sync/glue/sync_frontend.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/sessions2/sessions_sync_manager.h"
35 #include "chrome/browser/sync/sync_prefs.h"
36 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
37 #include "content/public/browser/notification_observer.h"
38 #include "content/public/browser/notification_registrar.h"
39 #include "content/public/browser/notification_types.h"
40 #include "google_apis/gaia/google_service_auth_error.h"
41 #include "google_apis/gaia/oauth2_token_service.h"
42 #include "net/base/backoff_entry.h"
43 #include "sync/internal_api/public/base/model_type.h"
44 #include "sync/internal_api/public/engine/model_safe_worker.h"
45 #include "sync/internal_api/public/sync_manager_factory.h"
46 #include "sync/internal_api/public/util/experiments.h"
47 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
48 #include "sync/js/sync_js_controller.h"
52 class ProfileOAuth2TokenService
;
53 class ProfileSyncComponentsFactory
;
54 class SigninManagerBase
;
55 class SyncGlobalError
;
57 namespace browser_sync
{
58 class BackendMigrator
;
59 class ChangeProcessor
;
60 class DataTypeManager
;
64 class OpenTabsUIDelegate
;
65 class SessionModelAssociator
;
68 class SyncSessionSnapshot
;
69 } // namespace sessions
70 } // namespace browser_sync
73 class BaseTransaction
;
74 class NetworkResources
;
75 struct SyncCredentials
;
81 } // namespace sync_pb
83 using browser_sync::SessionsSyncManager
;
85 // ProfileSyncService is the layer between browser subsystems like bookmarks,
86 // and the sync backend. Each subsystem is logically thought of as being
89 // Individual datatypes can, at any point, be in a variety of stages of being
90 // "enabled". Here are some specific terms for concepts used in this class:
92 // 'Registered' (feature suppression for a datatype)
94 // When a datatype is registered, the user has the option of syncing it.
95 // The sync opt-in UI will show only registered types; a checkbox should
96 // never be shown for an unregistered type, and nor should it ever be
99 // A datatype is considered registered once RegisterDataTypeController
100 // has been called with that datatype's DataTypeController.
102 // 'Preferred' (user preferences and opt-out for a datatype)
104 // This means the user's opt-in or opt-out preference on a per-datatype
105 // basis. The sync service will try to make active exactly these types.
106 // If a user has opted out of syncing a particular datatype, it will
107 // be registered, but not preferred.
109 // This state is controlled by the ConfigurePreferredDataTypes and
110 // GetPreferredDataTypes. They are stored in the preferences system,
111 // and persist; though if a datatype is not registered, it cannot
112 // be a preferred datatype.
114 // 'Active' (run-time initialization of sync system for a datatype)
116 // An active datatype is a preferred datatype that is actively being
117 // synchronized: the syncer has been instructed to querying the server
118 // for this datatype, first-time merges have finished, and there is an
119 // actively installed ChangeProcessor that listens for changes to this
120 // datatype, propagating such changes into and out of the sync backend
123 // When a datatype is in the process of becoming active, it may be
124 // in some intermediate state. Those finer-grained intermediate states
125 // are differentiated by the DataTypeController state.
127 // Sync Configuration:
129 // Sync configuration is accomplished via the following APIs:
130 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
131 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
132 // using the passed passphrase.
133 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
136 // Additionally, the current sync configuration can be fetched by calling
137 // * GetRegisteredDataTypes()
138 // * GetPreferredDataTypes()
139 // * GetActiveDataTypes()
140 // * IsUsingSecondaryPassphrase()
141 // * EncryptEverythingEnabled()
142 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
144 // The "sync everything" state cannot be read from ProfileSyncService, but
145 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
147 // Initial sync setup:
149 // For privacy reasons, it is usually desirable to avoid syncing any data
150 // types until the user has finished setting up sync. There are two APIs
151 // that control the initial sync download:
153 // * SetSyncSetupCompleted()
154 // * SetSetupInProgress()
156 // SetSyncSetupCompleted() should be called once the user has finished setting
157 // up sync at least once on their account. SetSetupInProgress(true) should be
158 // called while the user is actively configuring their account, and then
159 // SetSetupInProgress(false) should be called when configuration is complete.
160 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
161 // been called, then the sync engine knows not to download any user data.
163 // When initial sync is complete, the UI code should call
164 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
165 // tell the sync engine that setup is completed and it can begin downloading
166 // data from the sync server.
168 class ProfileSyncService
169 : public ProfileSyncServiceBase
,
170 public browser_sync::SyncFrontend
,
171 public browser_sync::SyncPrefObserver
,
172 public browser_sync::DataTypeManagerObserver
,
173 public syncer::UnrecoverableErrorHandler
,
174 public content::NotificationObserver
,
175 public BrowserContextKeyedService
,
176 public browser_sync::DataTypeEncryptionHandler
,
177 public OAuth2TokenService::Consumer
,
178 public OAuth2TokenService::Observer
,
179 public SessionsSyncManager::SyncInternalApiDelegate
{
181 typedef browser_sync::SyncBackendHost::Status Status
;
183 // Status of sync server connection, sync token and token request.
184 struct SyncTokenStatus
{
188 // Sync server connection status reported by sync backend.
189 base::Time connection_status_update_time
;
190 syncer::ConnectionStatus connection_status
;
192 // Times when OAuth2 access token is requested and received.
193 base::Time token_request_time
;
194 base::Time token_receive_time
;
196 // Error returned by OAuth2TokenService for token request and time when
197 // next request is scheduled.
198 GoogleServiceAuthError last_get_token_error
;
199 base::Time next_token_request_time
;
202 enum SyncEventCodes
{
203 MIN_SYNC_EVENT_CODE
= 0,
205 // Events starting the sync service.
206 START_FROM_NTP
= 1, // Sync was started from the ad in NTP
207 START_FROM_WRENCH
= 2, // Sync was started from the Wrench menu.
208 START_FROM_OPTIONS
= 3, // Sync was started from Wrench->Options.
209 START_FROM_BOOKMARK_MANAGER
= 4, // Sync was started from Bookmark manager.
210 START_FROM_PROFILE_MENU
= 5, // Sync was started from multiprofile menu.
211 START_FROM_URL
= 6, // Sync was started from a typed URL.
213 // Events regarding cancellation of the signon process of sync.
214 CANCEL_FROM_SIGNON_WITHOUT_AUTH
= 10, // Cancelled before submitting
215 // username and password.
216 CANCEL_DURING_SIGNON
= 11, // Cancelled after auth.
217 CANCEL_DURING_CONFIGURE
= 12, // Cancelled before choosing data
218 // types and clicking OK.
219 // Events resulting in the stoppage of sync service.
220 STOP_FROM_OPTIONS
= 20, // Sync was stopped from Wrench->Options.
221 STOP_FROM_ADVANCED_DIALOG
= 21, // Sync was stopped via advanced settings.
223 // Miscellaneous events caused by sync service.
228 // Defines the type of behavior the sync engine should use. If configured for
229 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted()
230 // and start downloading data types as soon as sync credentials are available
231 // (a signed-in username and a "chromiumsync" token).
232 // If configured for MANUAL_START, sync will not start until the user
233 // completes sync setup, at which point the UI makes an explicit call to
234 // SetSyncSetupCompleted().
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
,
257 // Default sync server URL.
258 static const char* kSyncServerUrl
;
259 // Sync server URL for dev channel users
260 static const char* kDevServerUrl
;
262 // Takes ownership of |factory|.
263 ProfileSyncService(ProfileSyncComponentsFactory
* factory
,
265 SigninManagerBase
* signin
,
266 ProfileOAuth2TokenService
* oauth2_token_service
,
267 StartBehavior start_behavior
);
268 virtual ~ProfileSyncService();
270 // Initializes the object. This must be called at most once, and
271 // immediately after an object of this class is constructed.
274 virtual void SetSyncSetupCompleted();
276 // ProfileSyncServiceBase implementation.
277 virtual bool HasSyncSetupCompleted() const OVERRIDE
;
278 virtual bool ShouldPushChanges() OVERRIDE
;
279 virtual syncer::ModelTypeSet
GetActiveDataTypes() const OVERRIDE
;
280 virtual void AddObserver(ProfileSyncServiceBase::Observer
* observer
) OVERRIDE
;
281 virtual void RemoveObserver(
282 ProfileSyncServiceBase::Observer
* observer
) OVERRIDE
;
283 virtual bool HasObserver(
284 ProfileSyncServiceBase::Observer
* observer
) const OVERRIDE
;
286 void RegisterAuthNotifications();
287 void UnregisterAuthNotifications();
289 // Returns true if sync is enabled/not suppressed and the user is logged in.
290 // (being logged in does not mean that tokens are available - tokens may
291 // be missing because they have not loaded yet, or because they were deleted
292 // due to http://crbug.com/121755).
293 // Virtual to enable mocking in tests.
294 virtual bool IsSyncEnabledAndLoggedIn();
296 // Return whether OAuth2 refresh token is loaded and available for the backend
297 // to start up. Virtual to enable mocking in tests.
298 virtual bool IsOAuthRefreshTokenAvailable();
300 // Registers a data type controller with the sync service. This
301 // makes the data type controller available for use, it does not
302 // enable or activate the synchronization of the data type (see
303 // ActivateDataType). Takes ownership of the pointer.
304 void RegisterDataTypeController(
305 browser_sync::DataTypeController
* data_type_controller
);
307 // Returns the session model associator associated with this type, but only if
308 // the associator is running. If it is doing anything else, it will return
311 // *** DONT USE THIS ANYMORE! ***
312 // If you think you want to use this, think again! Can you use
313 // GetOpenTabsUIDelegate instead?
314 // TODO(tim): Remove this method.
315 virtual browser_sync::SessionModelAssociator
*
316 GetSessionModelAssociatorDeprecated();
318 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
319 // currently syncing, returns NULL.
320 virtual browser_sync::OpenTabsUIDelegate
* GetOpenTabsUIDelegate();
322 // Returns the SyncableService for syncer::SESSIONS.
323 virtual syncer::SyncableService
* GetSessionsSyncableService();
325 // SyncInternalApiDelegate implementation.
327 // Returns sync's representation of the local device info.
328 // Return value is an empty scoped_ptr if the device info is unavailable.
329 virtual scoped_ptr
<browser_sync::DeviceInfo
> GetLocalDeviceInfo()
332 // Gets the guid for the local device. Can be used by other layers to
333 // to distinguish sync data that belongs to the local device vs data
334 // that belongs to remote devices. Returns empty string if sync is not
335 // initialized. The GUID is not persistent across Chrome signout/signin.
336 // If you sign out of Chrome and sign in, a new GUID is generated.
337 virtual std::string
GetLocalSyncCacheGUID() const OVERRIDE
;
339 // Returns sync's representation of the device info for a client identified
340 // by |client_id|. Return value is an empty scoped ptr if the device info
342 virtual scoped_ptr
<browser_sync::DeviceInfo
> GetDeviceInfo(
343 const std::string
& client_id
) const;
345 // Gets the device info for all devices signed into the account associated
346 // with this profile.
347 virtual ScopedVector
<browser_sync::DeviceInfo
> GetAllSignedInDevices() const;
349 // Notifies the observer of any device info changes.
350 virtual void AddObserverForDeviceInfoChange(
351 browser_sync::SyncedDeviceTracker::Observer
* observer
);
353 // Removes the observer from device info notification.
354 virtual void RemoveObserverForDeviceInfoChange(
355 browser_sync::SyncedDeviceTracker::Observer
* observer
);
357 // Fills state_map with a map of current data types that are possible to
358 // sync, as well as their states.
359 void GetDataTypeControllerStates(
360 browser_sync::DataTypeController::StateMap
* state_map
) const;
362 // Disables sync for user. Use ShowLoginDialog to enable.
363 virtual void DisableForUser();
365 // SyncFrontend implementation.
366 virtual void OnBackendInitialized(
367 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
368 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
370 bool success
) OVERRIDE
;
371 virtual void OnSyncCycleCompleted() OVERRIDE
;
372 virtual void OnSyncConfigureRetry() OVERRIDE
;
373 virtual void OnConnectionStatusChange(
374 syncer::ConnectionStatus status
) OVERRIDE
;
375 virtual void OnStopSyncingPermanently() OVERRIDE
;
376 virtual void OnPassphraseRequired(
377 syncer::PassphraseRequiredReason reason
,
378 const sync_pb::EncryptedData
& pending_keys
) OVERRIDE
;
379 virtual void OnPassphraseAccepted() OVERRIDE
;
380 virtual void OnEncryptedTypesChanged(
381 syncer::ModelTypeSet encrypted_types
,
382 bool encrypt_everything
) OVERRIDE
;
383 virtual void OnEncryptionComplete() OVERRIDE
;
384 virtual void OnMigrationNeededForTypes(
385 syncer::ModelTypeSet types
) OVERRIDE
;
386 virtual void OnExperimentsChanged(
387 const syncer::Experiments
& experiments
) OVERRIDE
;
388 virtual void OnActionableError(
389 const syncer::SyncProtocolError
& error
) OVERRIDE
;
391 // DataTypeManagerObserver implementation.
392 virtual void OnConfigureDone(
393 const browser_sync::DataTypeManager::ConfigureResult
& result
) OVERRIDE
;
394 virtual void OnConfigureRetry() OVERRIDE
;
395 virtual void OnConfigureStart() OVERRIDE
;
397 // DataTypeEncryptionHandler implementation.
398 virtual bool IsPassphraseRequired() const OVERRIDE
;
399 virtual syncer::ModelTypeSet
GetEncryptedDataTypes() const OVERRIDE
;
401 // Called when a user chooses which data types to sync as part of the sync
402 // setup wizard. |sync_everything| represents whether they chose the
403 // "keep everything synced" option; if true, |chosen_types| will be ignored
404 // and all data types will be synced. |sync_everything| means "sync all
405 // current and future data types."
406 virtual void OnUserChoseDatatypes(bool sync_everything
,
407 syncer::ModelTypeSet chosen_types
);
409 // Get the sync status code.
410 SyncStatusSummary
QuerySyncStatusSummary();
412 // Get a description of the sync status for displaying in the user interface.
413 std::string
QuerySyncStatusSummaryString();
415 // Initializes a struct of status indicators with data from the backend.
416 // Returns false if the backend was not available for querying; in that case
417 // the struct will be filled with default data.
418 virtual bool QueryDetailedSyncStatus(
419 browser_sync::SyncBackendHost::Status
* result
);
421 virtual const GoogleServiceAuthError
& GetAuthError() const;
423 // Returns true if initial sync setup is in progress (does not return true
424 // if the user is customizing sync after already completing setup once).
425 // ProfileSyncService uses this to determine if it's OK to start syncing, or
426 // if the user is still setting up the initial sync configuration.
427 virtual bool FirstSetupInProgress() const;
429 // Called by the UI to notify the ProfileSyncService that UI is visible so it
430 // will not start syncing. This tells sync whether it's safe to start
431 // downloading data types yet (we don't start syncing until after sync setup
432 // is complete). The UI calls this as soon as any part of the signin wizard is
433 // displayed (even just the login UI).
434 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
435 // that data download starts.
436 virtual void SetSetupInProgress(bool setup_in_progress
);
438 // Returns true if the SyncBackendHost has told us it's ready to accept
440 // [REMARK] - it is safe to call this function only from the ui thread.
441 // because the variable is not thread safe and should only be accessed from
442 // single thread. If we want multiple threads to access this(and there is
443 // currently no need to do so) we need to protect this with a lock.
444 // TODO(timsteele): What happens if the bookmark model is loaded, a change
445 // takes place, and the backend isn't initialized yet?
446 virtual bool sync_initialized() const;
448 virtual bool HasUnrecoverableError() const;
449 const std::string
& unrecoverable_error_message() {
450 return unrecoverable_error_message_
;
452 tracked_objects::Location
unrecoverable_error_location() {
453 return unrecoverable_error_location_
;
456 // Returns true if OnPassphraseRequired has been called for decryption and
457 // we have an encrypted data type enabled.
458 virtual bool IsPassphraseRequiredForDecryption() const;
460 syncer::PassphraseRequiredReason
passphrase_required_reason() const {
461 return passphrase_required_reason_
;
464 // Returns a user-friendly string form of last synced time (in minutes).
465 virtual base::string16
GetLastSyncedTimeString() const;
467 // Returns a human readable string describing backend initialization state.
468 std::string
GetBackendInitializationStateString() const;
470 // Returns true if startup is suppressed (i.e. user has stopped syncing via
471 // the google dashboard).
472 virtual bool IsStartSuppressed() const;
474 ProfileSyncComponentsFactory
* factory() { return factory_
.get(); }
476 // The profile we are syncing for.
477 Profile
* profile() const { return profile_
; }
479 // Returns a weak pointer to the service's JsController.
480 // Overrideable for testing purposes.
481 virtual base::WeakPtr
<syncer::JsController
> GetJsController();
483 // Record stats on various events.
484 static void SyncEvent(SyncEventCodes code
);
486 // Returns whether sync is enabled. Sync can be enabled/disabled both
487 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
488 // command-line switches).
489 // Profile::IsSyncAccessible() is probably a better signal than this function.
490 // This function can be called from any thread, and the implementation doesn't
491 // assume it's running on the UI thread.
492 static bool IsSyncEnabled();
494 // Returns whether sync is managed, i.e. controlled by configuration
495 // management. If so, the user is not allowed to configure sync.
496 virtual bool IsManaged() const;
498 // syncer::UnrecoverableErrorHandler implementation.
499 virtual void OnUnrecoverableError(
500 const tracked_objects::Location
& from_here
,
501 const std::string
& message
) OVERRIDE
;
503 // Called when a datatype wishes to disable itself due to having hit an
504 // unrecoverable error.
505 virtual void DisableBrokenDatatype(
506 syncer::ModelType type
,
507 const tracked_objects::Location
& from_here
,
508 std::string message
);
510 // The functions below (until ActivateDataType()) should only be
511 // called if sync_initialized() is true.
513 // TODO(akalin): This is called mostly by ModelAssociators and
514 // tests. Figure out how to pass the handle to the ModelAssociators
515 // directly, figure out how to expose this to tests, and remove this
517 virtual syncer::UserShare
* GetUserShare() const;
519 // TODO(akalin): These two functions are used only by
520 // ProfileSyncServiceHarness. Figure out a different way to expose
521 // this info to that class, and remove these functions.
523 virtual syncer::sessions::SyncSessionSnapshot
524 GetLastSessionSnapshot() const;
526 // Returns whether or not the underlying sync engine has made any
527 // local changes to items that have not yet been synced with the
529 bool HasUnsyncedItems() const;
531 // Used by ProfileSyncServiceHarness. May return NULL.
532 browser_sync::BackendMigrator
* GetBackendMigratorForTest();
534 // Used by tests to inspect interaction with OAuth2TokenService.
535 bool IsRetryingAccessTokenFetchForTest() const;
537 // Used by tests to inspect the OAuth2 access tokens used by PSS.
538 std::string
GetAccessTokenForTest() const;
540 // TODO(sync): This is only used in tests. Can we remove it?
541 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo
* out
) const;
543 // Returns a ListValue indicating the status of all registered types.
546 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
547 // where <name> is a type's name, <value> is a string providing details for
548 // the type's status, and <status> is one of "error", "warning" or "ok"
549 // dpending on the type's current status.
551 // This function is used by sync_ui_util.cc to help populate the about:sync
552 // page. It returns a ListValue rather than a DictionaryValue in part to make
553 // it easier to iterate over its elements when constructing that page.
554 base::Value
* GetTypeStatusMap() const;
556 // Overridden by tests.
557 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
558 virtual void ActivateDataType(
559 syncer::ModelType type
, syncer::ModelSafeGroup group
,
560 browser_sync::ChangeProcessor
* change_processor
);
561 virtual void DeactivateDataType(syncer::ModelType type
);
563 // SyncPrefObserver implementation.
564 virtual void OnSyncManagedPrefChange(bool is_sync_managed
) OVERRIDE
;
566 // content::NotificationObserver implementation.
567 virtual void Observe(int type
,
568 const content::NotificationSource
& source
,
569 const content::NotificationDetails
& details
) OVERRIDE
;
571 // Changes which data types we're going to be syncing to |preferred_types|.
572 // If it is running, the DataTypeManager will be instructed to reconfigure
573 // the sync backend so that exactly these datatypes are actively synced. See
574 // class comment for more on what it means for a datatype to be Preferred.
575 virtual void ChangePreferredDataTypes(
576 syncer::ModelTypeSet preferred_types
);
578 // Returns the set of types which are preferred for enabling. This is a
579 // superset of the active types (see GetActiveDataTypes()).
580 virtual syncer::ModelTypeSet
GetPreferredDataTypes() const;
582 // Gets the set of all data types that could be allowed (the set that
583 // should be advertised to the user). These will typically only change
584 // via a command-line option. See class comment for more on what it means
585 // for a datatype to be Registered.
586 virtual syncer::ModelTypeSet
GetRegisteredDataTypes() const;
588 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
589 // for sensitive data types. Caller must be holding a
590 // syncapi::BaseTransaction to ensure thread safety.
591 virtual bool IsCryptographerReady(
592 const syncer::BaseTransaction
* trans
) const;
594 // Returns true if a secondary (explicit) passphrase is being used. It is not
595 // legal to call this method before the backend is initialized.
596 virtual bool IsUsingSecondaryPassphrase() const;
598 // Returns the actual passphrase type being used for encryption.
599 virtual syncer::PassphraseType
GetPassphraseType() const;
601 // Returns the time the current explicit passphrase (if any), was set.
602 // If no secondary passphrase is in use, or no time is available, returns an
604 virtual base::Time
GetExplicitPassphraseTime() const;
606 // Note about setting passphrases: There are different scenarios under which
607 // we might want to apply a passphrase. It could be for first-time encryption,
608 // re-encryption, or for decryption by clients that sign in at a later time.
609 // In addition, encryption can either be done using a custom passphrase, or by
610 // reusing the GAIA password. Depending on what is happening in the system,
611 // callers should determine which of the two methods below must be used.
613 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
614 // specifies whether the passphrase is a custom passphrase or the GAIA
615 // password being reused as a passphrase.
616 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
617 // passphrase with this API.
618 virtual void SetEncryptionPassphrase(const std::string
& passphrase
,
619 PassphraseType type
);
621 // Asynchronously decrypts pending keys using |passphrase|. Returns false
622 // immediately if the passphrase could not be used to decrypt a locally cached
623 // copy of encrypted keys; returns true otherwise.
624 virtual bool SetDecryptionPassphrase(const std::string
& passphrase
)
627 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
628 // after calling this to force the encryption to occur.
629 virtual void EnableEncryptEverything();
631 // Returns true if we are currently set to encrypt all the sync data. Note:
632 // this is based on the cryptographer's settings, so if the user has recently
633 // requested encryption to be turned on, this may not be true yet. For that,
634 // encryption_pending() must be checked.
635 virtual bool EncryptEverythingEnabled() const;
637 // Returns true if the syncer is waiting for new datatypes to be encrypted.
638 virtual bool encryption_pending() const;
640 const GURL
& sync_service_url() const { return sync_service_url_
; }
641 bool auto_start_enabled() const { return auto_start_enabled_
; }
642 SigninManagerBase
* signin() const { return signin_
; }
643 bool setup_in_progress() const { return setup_in_progress_
; }
645 // Stops the sync backend and sets the flag for suppressing sync startup.
646 void StopAndSuppress();
648 // Resets the flag for suppressing sync startup and starts the sync backend.
649 virtual void UnsuppressAndStart();
651 // Marks all currently registered types as "acknowledged" so we won't prompt
652 // the user about them any more.
653 void AcknowledgeSyncedTypes();
655 SyncGlobalError
* sync_global_error() { return sync_global_error_
.get(); }
657 // TODO(sync): This is only used in tests. Can we remove it?
658 const browser_sync::FailedDataTypesHandler
& failed_data_types_handler() const;
660 browser_sync::DataTypeManager::ConfigureStatus
configure_status() {
661 return configure_status_
;
664 // If true, the ProfileSyncService has detected that a new GAIA signin has
665 // succeeded, and is waiting for initialization to complete. This is used by
666 // the UI to differentiate between a new auth error (encountered as part of
667 // the initialization process) and a pre-existing auth error that just hasn't
668 // been cleared yet. Virtual for testing purposes.
669 virtual bool waiting_for_auth() const;
671 // The set of currently enabled sync experiments.
672 const syncer::Experiments
& current_experiments() const;
674 // OAuth2TokenService::Consumer implementation.
675 virtual void OnGetTokenSuccess(
676 const OAuth2TokenService::Request
* request
,
677 const std::string
& access_token
,
678 const base::Time
& expiration_time
) OVERRIDE
;
679 virtual void OnGetTokenFailure(
680 const OAuth2TokenService::Request
* request
,
681 const GoogleServiceAuthError
& error
) OVERRIDE
;
683 // OAuth2TokenService::Observer implementation.
684 virtual void OnRefreshTokenAvailable(const std::string
& account_id
) OVERRIDE
;
685 virtual void OnRefreshTokenRevoked(const std::string
& account_id
) OVERRIDE
;
686 virtual void OnRefreshTokensLoaded() OVERRIDE
;
688 // BrowserContextKeyedService implementation. This must be called exactly
689 // once (before this object is destroyed).
690 virtual void Shutdown() OVERRIDE
;
692 // Called when a datatype (SyncableService) has a need for sync to start
693 // ASAP, presumably because a local change event has occurred but we're
694 // still in deferred start mode, meaning the SyncableService hasn't been
695 // told to MergeDataAndStartSyncing yet.
696 void OnDataTypeRequestsSyncStartup(syncer::ModelType type
);
698 // Return sync token status.
699 SyncTokenStatus
GetSyncTokenStatus() const;
701 browser_sync::FaviconCache
* GetFaviconCache();
703 // Overrides the NetworkResources used for Sync connections.
704 // This function takes ownership of |network_resources|.
705 void OverrideNetworkResourcesForTest(
706 scoped_ptr
<syncer::NetworkResources
> network_resources
);
708 virtual bool IsSessionsDataTypeControllerRunning() const;
711 // Helper to configure the priority data types.
712 void ConfigurePriorityDataTypes();
714 // Helper to install and configure a data type manager.
715 void ConfigureDataTypeManager();
717 // Shuts down the backend sync components.
718 // |option| indicates if syncing is being disabled or not, and whether
719 // to claim ownership of sync thread from backend.
720 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option
);
722 // Return SyncCredentials from the OAuth2TokenService.
723 syncer::SyncCredentials
GetCredentials();
725 virtual syncer::WeakHandle
<syncer::JsEventHandler
> GetJsEventHandler();
727 // Test need to override this to create backends that allow setting up
728 // initial conditions, such as populating sync nodes.
730 // TODO(akalin): Figure out a better way to do this. Ideally, we'd
731 // construct the backend outside this class and pass it in to the
732 // contructor or Initialize().
733 virtual void CreateBackend();
735 const browser_sync::DataTypeController::TypeMap
& data_type_controllers() {
736 return data_type_controllers_
;
739 // Helper method for managing encryption UI.
740 bool IsEncryptedDatatypeEnabled() const;
742 // Helper for OnUnrecoverableError.
743 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
744 // and in SyncBackendHost::Shutdown.
745 void OnUnrecoverableErrorImpl(
746 const tracked_objects::Location
& from_here
,
747 const std::string
& message
,
748 bool delete_sync_database
);
750 // This is a cache of the last authentication response we received from the
751 // sync server. The UI queries this to display appropriate messaging to the
753 GoogleServiceAuthError last_auth_error_
;
755 // Our asynchronous backend to communicate with sync components living on
757 scoped_ptr
<browser_sync::SyncBackendHost
> backend_
;
759 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
760 // was required for encryption, decryption with a cached passphrase, or
761 // because a new passphrase is required?
762 syncer::PassphraseRequiredReason passphrase_required_reason_
;
765 enum UnrecoverableErrorReason
{
768 ERROR_REASON_BACKEND_INIT_FAILURE
,
769 ERROR_REASON_CONFIGURATION_RETRY
,
770 ERROR_REASON_CONFIGURATION_FAILURE
,
771 ERROR_REASON_ACTIONABLE_ERROR
,
775 enum AuthErrorMetric
{
776 AUTH_ERROR_ENCOUNTERED
,
781 friend class ProfileSyncServicePasswordTest
;
782 friend class SyncTest
;
783 friend class TestProfileSyncService
;
784 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest
, InitialState
);
786 // Update the last auth error and notify observers of error state.
787 void UpdateAuthErrorState(const GoogleServiceAuthError
& error
);
789 // Detects and attempts to recover from a previous improper datatype
790 // configuration where Keep Everything Synced and the preferred types were
791 // not correctly set.
792 void TrySyncDatatypePrefRecovery();
794 // Starts up sync if it is not suppressed and preconditions are met.
795 // Called from Initialize() and UnsuppressAndStart().
798 // Puts the backend's sync scheduler into NORMAL mode.
799 // Called when configuration is complete.
800 void StartSyncingWithServer();
802 // Called when we've determined that we don't need a passphrase (either
803 // because OnPassphraseAccepted() was called, or because we've gotten a
804 // OnPassphraseRequired() but no data types are enabled).
805 void ResolvePassphraseRequired();
807 // During initial signin, ProfileSyncService caches the user's signin
808 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
809 // This routine is invoked once the backend has started up to use the
810 // cached passphrase and clear it out when it is done.
811 void ConsumeCachedPassphraseIfPossible();
813 // RequestAccessToken initiates RPC to request downscoped access token from
814 // refresh token. This happens when a new OAuth2 login token is loaded and
815 // when sync server returns AUTH_ERROR which indicates it is time to refresh
817 virtual void RequestAccessToken();
819 // If |delete_sync_data_folder| is true, then this method will delete all
820 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
821 void InitializeBackend(bool delete_sync_data_folder
);
823 // Initializes the various settings from the command line.
826 // Sets the last synced time to the current time.
827 void UpdateLastSyncedTime();
829 void NotifyObservers();
830 void NotifySyncCycleCompleted();
832 void ClearStaleErrors();
834 void ClearUnrecoverableError();
836 enum StartUpDeferredOption
{
837 STARTUP_BACKEND_DEFERRED
,
840 void StartUp(StartUpDeferredOption deferred_option
);
842 // Starts up the backend sync components.
843 void StartUpSlowBackendComponents();
845 // About-flags experiment names for datatypes that aren't enabled by default
847 static std::string
GetExperimentNameForDataType(
848 syncer::ModelType data_type
);
850 // Create and register a new datatype controller.
851 void RegisterNewDataType(syncer::ModelType data_type
);
853 // Reconfigures the data type manager with the latest enabled types.
854 // Note: Does not initialize the backend if it is not already initialized.
855 // This function needs to be called only after sync has been initialized
856 // (i.e.,only for reconfigurations). The reason we don't initialize the
857 // backend is because if we had encountered an unrecoverable error we don't
858 // want to startup once more.
859 virtual void ReconfigureDatatypeManager();
861 // Called when the user changes the sync configuration, to update the UMA
863 void UpdateSelectedTypesHistogram(
864 bool sync_everything
,
865 const syncer::ModelTypeSet chosen_types
) const;
867 #if defined(OS_CHROMEOS)
868 // Refresh spare sync bootstrap token for re-enabling the sync service.
869 // Called on successful sign-in notifications.
870 void RefreshSpareBootstrapToken(const std::string
& passphrase
);
873 // Internal unrecoverable error handler. Used to track error reason via
874 // Sync.UnrecoverableErrors histogram.
875 void OnInternalUnrecoverableError(const tracked_objects::Location
& from_here
,
876 const std::string
& message
,
877 bool delete_sync_database
,
878 UnrecoverableErrorReason reason
);
880 // Returns the username (in form of an email address) that should be used in
882 std::string
GetEffectiveUsername();
884 // Returns the account ID to use to get tokens.
885 std::string
GetAccountIdToUse();
887 // Factory used to create various dependent objects.
888 scoped_ptr
<ProfileSyncComponentsFactory
> factory_
;
890 // The profile whose data we are synchronizing.
893 // The class that handles getting, setting, and persisting sync
895 browser_sync::SyncPrefs sync_prefs_
;
897 // TODO(ncarter): Put this in a profile, once there is UI for it.
898 // This specifies where to find the sync server.
899 GURL sync_service_url_
;
901 // The last time we detected a successful transition from SYNCING state.
902 // Our backend notifies us whenever we should take a new snapshot.
903 base::Time last_synced_time_
;
905 // The time that StartUp() is called. This member is zero if StartUp() has
906 // never been called, and is reset to zero once OnBackendInitialized() is
908 base::Time start_up_time_
;
910 // Whether we have received a signal from a SyncableService requesting that
911 // sync starts as soon as possible.
912 // TODO(tim): Move this and other TryStart related logic + state to separate
914 bool data_type_requested_sync_startup_
;
916 // The time that OnConfigureStart is called. This member is zero if
917 // OnConfigureStart has not yet been called, and is reset to zero once
918 // OnConfigureDone is called.
919 base::Time sync_configure_start_time_
;
921 // Indicates if this is the first time sync is being configured. This value
922 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
923 bool is_first_time_sync_configure_
;
925 // List of available data type controllers.
926 browser_sync::DataTypeController::TypeMap data_type_controllers_
;
928 // Whether the SyncBackendHost has been initialized.
929 bool backend_initialized_
;
931 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
932 // ProfileSyncService from starting backend till browser restarted or user
934 bool sync_disabled_by_admin_
;
936 // Set to true if a signin has completed but we're still waiting for the
937 // backend to refresh its credentials.
938 bool is_auth_in_progress_
;
940 // Encapsulates user signin - used to set/get the user's authenticated
942 SigninManagerBase
* signin_
;
944 // Information describing an unrecoverable error.
945 UnrecoverableErrorReason unrecoverable_error_reason_
;
946 std::string unrecoverable_error_message_
;
947 tracked_objects::Location unrecoverable_error_location_
;
949 // Manages the start and stop of the various data types.
950 scoped_ptr
<browser_sync::DataTypeManager
> data_type_manager_
;
952 ObserverList
<ProfileSyncServiceBase::Observer
> observers_
;
954 syncer::SyncJsController sync_js_controller_
;
956 content::NotificationRegistrar registrar_
;
958 // This allows us to gracefully handle an ABORTED return code from the
959 // DataTypeManager in the event that the server informed us to cease and
960 // desist syncing immediately.
961 bool expect_sync_configuration_aborted_
;
963 // Sometimes we need to temporarily hold on to a passphrase because we don't
964 // yet have a backend to send it to. This happens during initialization as
965 // we don't StartUp until we have a valid token, which happens after valid
966 // credentials were provided.
967 std::string cached_passphrase_
;
969 // The current set of encrypted types. Always a superset of
970 // syncer::Cryptographer::SensitiveTypes().
971 syncer::ModelTypeSet encrypted_types_
;
973 // Whether we want to encrypt everything.
974 bool encrypt_everything_
;
976 // Whether we're waiting for an attempt to encryption all sync data to
977 // complete. We track this at this layer in order to allow the user to cancel
978 // if they e.g. don't remember their explicit passphrase.
979 bool encryption_pending_
;
981 // If true, we want to automatically start sync signin whenever we have
982 // credentials (user doesn't need to go through the startup flow). This is
983 // typically enabled on platforms (like ChromeOS) that have their own
984 // distinct signin flow.
985 const bool auto_start_enabled_
;
987 scoped_ptr
<browser_sync::BackendMigrator
> migrator_
;
989 // This is the last |SyncProtocolError| we received from the server that had
990 // an action set on it.
991 syncer::SyncProtocolError last_actionable_error_
;
993 // This is used to show sync errors in the wrench menu.
994 scoped_ptr
<SyncGlobalError
> sync_global_error_
;
996 // Tracks the set of failed data types (those that encounter an error
997 // or must delay loading for some reason).
998 browser_sync::FailedDataTypesHandler failed_data_types_handler_
;
1000 browser_sync::DataTypeManager::ConfigureStatus configure_status_
;
1002 // If |true|, there is setup UI visible so we should not start downloading
1004 bool setup_in_progress_
;
1006 // The set of currently enabled sync experiments.
1007 syncer::Experiments current_experiments_
;
1009 // Sync's internal debug info listener. Used to record datatype configuration
1010 // and association information.
1011 syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
> debug_info_listener_
;
1013 // A thread where all the sync operations happen.
1015 // * Created when backend starts for the first time.
1016 // * If sync is disabled, PSS claims ownership from backend.
1017 // * If sync is reenabled, PSS passes ownership to new backend.
1018 scoped_ptr
<base::Thread
> sync_thread_
;
1020 // ProfileSyncService uses this service to get access tokens.
1021 ProfileOAuth2TokenService
* oauth2_token_service_
;
1023 // ProfileSyncService needs to remember access token in order to invalidate it
1024 // with OAuth2TokenService.
1025 std::string access_token_
;
1027 // ProfileSyncService needs to hold reference to access_token_request_ for
1028 // the duration of request in order to receive callbacks.
1029 scoped_ptr
<OAuth2TokenService::Request
> access_token_request_
;
1031 // If RequestAccessToken fails with transient error then retry requesting
1032 // access token with exponential backoff.
1033 base::OneShotTimer
<ProfileSyncService
> request_access_token_retry_timer_
;
1034 net::BackoffEntry request_access_token_backoff_
;
1036 base::WeakPtrFactory
<ProfileSyncService
> weak_factory_
;
1038 // States related to sync token and connection.
1039 base::Time connection_status_update_time_
;
1040 syncer::ConnectionStatus connection_status_
;
1041 base::Time token_request_time_
;
1042 base::Time token_receive_time_
;
1043 GoogleServiceAuthError last_get_token_error_
;
1044 base::Time next_token_request_time_
;
1046 scoped_ptr
<SessionsSyncManager
> sessions_sync_manager_
;
1048 scoped_ptr
<syncer::NetworkResources
> network_resources_
;
1050 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService
);
1053 bool ShouldShowActionOnUI(
1054 const syncer::SyncProtocolError
& error
);
1057 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_