NaCl: Update revision in DEPS, r12770 -> r12773
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob10777c95b64bdff6545797fb1013802ad964ee5f
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_
8 #include <string>
9 #include <utility>
10 #include <vector>
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/sync_backend_host.h"
25 #include "chrome/browser/sync/glue/synced_device_tracker.h"
26 #include "chrome/browser/sync/profile_sync_service_base.h"
27 #include "chrome/browser/sync/profile_sync_service_observer.h"
28 #include "chrome/browser/sync/sessions2/sessions_sync_manager.h"
29 #include "chrome/browser/sync/sync_prefs.h"
30 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
31 #include "components/sync_driver/data_type_controller.h"
32 #include "components/sync_driver/data_type_encryption_handler.h"
33 #include "components/sync_driver/data_type_manager.h"
34 #include "components/sync_driver/data_type_manager_observer.h"
35 #include "components/sync_driver/failed_data_types_handler.h"
36 #include "components/sync_driver/sync_frontend.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"
49 #include "url/gurl.h"
51 class ManagedUserSigninManagerWrapper;
52 class Profile;
53 class ProfileOAuth2TokenService;
54 class ProfileSyncComponentsFactory;
55 class SigninManagerBase;
56 class SyncGlobalError;
58 namespace browser_sync {
59 class BackendMigrator;
60 class ChangeProcessor;
61 class DataTypeManager;
62 class DeviceInfo;
63 class FaviconCache;
64 class JsController;
65 class OpenTabsUIDelegate;
66 class SessionModelAssociator;
68 namespace sessions {
69 class SyncSessionSnapshot;
70 } // namespace sessions
71 } // namespace browser_sync
73 namespace syncer {
74 class BaseTransaction;
75 class NetworkResources;
76 struct SyncCredentials;
77 struct UserShare;
78 } // namespace syncer
80 namespace sync_pb {
81 class EncryptedData;
82 } // namespace sync_pb
84 using browser_sync::SessionsSyncManager;
86 // ProfileSyncService is the layer between browser subsystems like bookmarks,
87 // and the sync backend. Each subsystem is logically thought of as being
88 // a sync datatype.
90 // Individual datatypes can, at any point, be in a variety of stages of being
91 // "enabled". Here are some specific terms for concepts used in this class:
93 // 'Registered' (feature suppression for a datatype)
95 // When a datatype is registered, the user has the option of syncing it.
96 // The sync opt-in UI will show only registered types; a checkbox should
97 // never be shown for an unregistered type, and nor should it ever be
98 // synced.
100 // A datatype is considered registered once RegisterDataTypeController
101 // has been called with that datatype's DataTypeController.
103 // 'Preferred' (user preferences and opt-out for a datatype)
105 // This means the user's opt-in or opt-out preference on a per-datatype
106 // basis. The sync service will try to make active exactly these types.
107 // If a user has opted out of syncing a particular datatype, it will
108 // be registered, but not preferred.
110 // This state is controlled by the ConfigurePreferredDataTypes and
111 // GetPreferredDataTypes. They are stored in the preferences system,
112 // and persist; though if a datatype is not registered, it cannot
113 // be a preferred datatype.
115 // 'Active' (run-time initialization of sync system for a datatype)
117 // An active datatype is a preferred datatype that is actively being
118 // synchronized: the syncer has been instructed to querying the server
119 // for this datatype, first-time merges have finished, and there is an
120 // actively installed ChangeProcessor that listens for changes to this
121 // datatype, propagating such changes into and out of the sync backend
122 // as necessary.
124 // When a datatype is in the process of becoming active, it may be
125 // in some intermediate state. Those finer-grained intermediate states
126 // are differentiated by the DataTypeController state.
128 // Sync Configuration:
130 // Sync configuration is accomplished via the following APIs:
131 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
132 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
133 // using the passed passphrase.
134 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
135 // passphrase.
137 // Additionally, the current sync configuration can be fetched by calling
138 // * GetRegisteredDataTypes()
139 // * GetPreferredDataTypes()
140 // * GetActiveDataTypes()
141 // * IsUsingSecondaryPassphrase()
142 // * EncryptEverythingEnabled()
143 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
145 // The "sync everything" state cannot be read from ProfileSyncService, but
146 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
148 // Initial sync setup:
150 // For privacy reasons, it is usually desirable to avoid syncing any data
151 // types until the user has finished setting up sync. There are two APIs
152 // that control the initial sync download:
154 // * SetSyncSetupCompleted()
155 // * SetSetupInProgress()
157 // SetSyncSetupCompleted() should be called once the user has finished setting
158 // up sync at least once on their account. SetSetupInProgress(true) should be
159 // called while the user is actively configuring their account, and then
160 // SetSetupInProgress(false) should be called when configuration is complete.
161 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
162 // been called, then the sync engine knows not to download any user data.
164 // When initial sync is complete, the UI code should call
165 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
166 // tell the sync engine that setup is completed and it can begin downloading
167 // data from the sync server.
169 class ProfileSyncService
170 : public ProfileSyncServiceBase,
171 public browser_sync::SyncFrontend,
172 public browser_sync::SyncPrefObserver,
173 public browser_sync::DataTypeManagerObserver,
174 public syncer::UnrecoverableErrorHandler,
175 public content::NotificationObserver,
176 public BrowserContextKeyedService,
177 public browser_sync::DataTypeEncryptionHandler,
178 public OAuth2TokenService::Consumer,
179 public OAuth2TokenService::Observer,
180 public SessionsSyncManager::SyncInternalApiDelegate {
181 public:
182 typedef browser_sync::SyncBackendHost::Status Status;
184 // Status of sync server connection, sync token and token request.
185 struct SyncTokenStatus {
186 SyncTokenStatus();
187 ~SyncTokenStatus();
189 // Sync server connection status reported by sync backend.
190 base::Time connection_status_update_time;
191 syncer::ConnectionStatus connection_status;
193 // Times when OAuth2 access token is requested and received.
194 base::Time token_request_time;
195 base::Time token_receive_time;
197 // Error returned by OAuth2TokenService for token request and time when
198 // next request is scheduled.
199 GoogleServiceAuthError last_get_token_error;
200 base::Time next_token_request_time;
203 enum SyncEventCodes {
204 MIN_SYNC_EVENT_CODE = 0,
206 // Events starting the sync service.
207 START_FROM_NTP = 1, // Sync was started from the ad in NTP
208 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
209 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
210 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
211 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
212 START_FROM_URL = 6, // Sync was started from a typed URL.
214 // Events regarding cancellation of the signon process of sync.
215 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
216 // username and password.
217 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
218 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
219 // types and clicking OK.
220 // Events resulting in the stoppage of sync service.
221 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
222 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
224 // Miscellaneous events caused by sync service.
226 MAX_SYNC_EVENT_CODE
229 // Defines the type of behavior the sync engine should use. If configured for
230 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted()
231 // and start downloading data types as soon as sync credentials are available
232 // (a signed-in username and a "chromiumsync" token).
233 // If configured for MANUAL_START, sync will not start until the user
234 // completes sync setup, at which point the UI makes an explicit call to
235 // SetSyncSetupCompleted().
236 enum StartBehavior {
237 AUTO_START,
238 MANUAL_START,
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 {
250 UNRECOVERABLE_ERROR,
251 NOT_ENABLED,
252 SETUP_INCOMPLETE,
253 DATATYPES_NOT_INITIALIZED,
254 INITIALIZED,
255 UNKNOWN_ERROR,
258 // Default sync server URL.
259 static const char* kSyncServerUrl;
260 // Sync server URL for dev channel users
261 static const char* kDevServerUrl;
263 // Takes ownership of |factory| and |signin_wrapper|.
264 ProfileSyncService(ProfileSyncComponentsFactory* factory,
265 Profile* profile,
266 ManagedUserSigninManagerWrapper* signin_wrapper,
267 ProfileOAuth2TokenService* oauth2_token_service,
268 StartBehavior start_behavior);
269 virtual ~ProfileSyncService();
271 // Initializes the object. This must be called at most once, and
272 // immediately after an object of this class is constructed.
273 void Initialize();
275 virtual void SetSyncSetupCompleted();
277 // ProfileSyncServiceBase implementation.
278 virtual bool HasSyncSetupCompleted() const OVERRIDE;
279 virtual bool ShouldPushChanges() OVERRIDE;
280 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
281 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
282 virtual void RemoveObserver(
283 ProfileSyncServiceBase::Observer* observer) OVERRIDE;
284 virtual bool HasObserver(
285 ProfileSyncServiceBase::Observer* observer) const OVERRIDE;
287 void RegisterAuthNotifications();
288 void UnregisterAuthNotifications();
290 // Returns true if sync is enabled/not suppressed and the user is logged in.
291 // (being logged in does not mean that tokens are available - tokens may
292 // be missing because they have not loaded yet, or because they were deleted
293 // due to http://crbug.com/121755).
294 // Virtual to enable mocking in tests.
295 virtual bool IsSyncEnabledAndLoggedIn();
297 // Return whether OAuth2 refresh token is loaded and available for the backend
298 // to start up. Virtual to enable mocking in tests.
299 virtual bool IsOAuthRefreshTokenAvailable();
301 // Registers a data type controller with the sync service. This
302 // makes the data type controller available for use, it does not
303 // enable or activate the synchronization of the data type (see
304 // ActivateDataType). Takes ownership of the pointer.
305 void RegisterDataTypeController(
306 browser_sync::DataTypeController* data_type_controller);
308 // Returns the session model associator associated with this type, but only if
309 // the associator is running. If it is doing anything else, it will return
310 // null.
312 // *** DONT USE THIS ANYMORE! ***
313 // If you think you want to use this, think again! Can you use
314 // GetOpenTabsUIDelegate instead?
315 // TODO(tim): Remove this method.
316 virtual browser_sync::SessionModelAssociator*
317 GetSessionModelAssociatorDeprecated();
319 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
320 // currently syncing, returns NULL.
321 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
323 // Returns the SyncableService for syncer::SESSIONS.
324 virtual syncer::SyncableService* GetSessionsSyncableService();
326 // SyncInternalApiDelegate implementation.
328 // Returns sync's representation of the local device info.
329 // Return value is an empty scoped_ptr if the device info is unavailable.
330 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo()
331 const OVERRIDE;
333 // Gets the guid for the local device. Can be used by other layers to
334 // to distinguish sync data that belongs to the local device vs data
335 // that belongs to remote devices. Returns empty string if sync is not
336 // initialized. The GUID is not persistent across Chrome signout/signin.
337 // If you sign out of Chrome and sign in, a new GUID is generated.
338 virtual std::string GetLocalSyncCacheGUID() const OVERRIDE;
340 // Returns sync's representation of the device info for a client identified
341 // by |client_id|. Return value is an empty scoped ptr if the device info
342 // is unavailable.
343 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
344 const std::string& client_id) const;
346 // Gets the device info for all devices signed into the account associated
347 // with this profile.
348 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const;
350 // Notifies the observer of any device info changes.
351 virtual void AddObserverForDeviceInfoChange(
352 browser_sync::SyncedDeviceTracker::Observer* observer);
354 // Removes the observer from device info notification.
355 virtual void RemoveObserverForDeviceInfoChange(
356 browser_sync::SyncedDeviceTracker::Observer* observer);
358 // Fills state_map with a map of current data types that are possible to
359 // sync, as well as their states.
360 void GetDataTypeControllerStates(
361 browser_sync::DataTypeController::StateMap* state_map) const;
363 // Disables sync for user. Use ShowLoginDialog to enable.
364 virtual void DisableForUser();
366 // Disables sync for the user and prevents it from starting on next restart.
367 virtual void StopSyncingPermanently();
369 // SyncFrontend implementation.
370 virtual void OnBackendInitialized(
371 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
372 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
373 debug_info_listener,
374 bool success) OVERRIDE;
375 virtual void OnSyncCycleCompleted() OVERRIDE;
376 virtual void OnSyncConfigureRetry() OVERRIDE;
377 virtual void OnConnectionStatusChange(
378 syncer::ConnectionStatus status) OVERRIDE;
379 virtual void OnPassphraseRequired(
380 syncer::PassphraseRequiredReason reason,
381 const sync_pb::EncryptedData& pending_keys) OVERRIDE;
382 virtual void OnPassphraseAccepted() OVERRIDE;
383 virtual void OnEncryptedTypesChanged(
384 syncer::ModelTypeSet encrypted_types,
385 bool encrypt_everything) OVERRIDE;
386 virtual void OnEncryptionComplete() OVERRIDE;
387 virtual void OnMigrationNeededForTypes(
388 syncer::ModelTypeSet types) OVERRIDE;
389 virtual void OnExperimentsChanged(
390 const syncer::Experiments& experiments) OVERRIDE;
391 virtual void OnActionableError(
392 const syncer::SyncProtocolError& error) OVERRIDE;
394 // DataTypeManagerObserver implementation.
395 virtual void OnConfigureDone(
396 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE;
397 virtual void OnConfigureRetry() OVERRIDE;
398 virtual void OnConfigureStart() OVERRIDE;
400 // DataTypeEncryptionHandler implementation.
401 virtual bool IsPassphraseRequired() const OVERRIDE;
402 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
404 // Called when a user chooses which data types to sync as part of the sync
405 // setup wizard. |sync_everything| represents whether they chose the
406 // "keep everything synced" option; if true, |chosen_types| will be ignored
407 // and all data types will be synced. |sync_everything| means "sync all
408 // current and future data types."
409 virtual void OnUserChoseDatatypes(bool sync_everything,
410 syncer::ModelTypeSet chosen_types);
412 // Get the sync status code.
413 SyncStatusSummary QuerySyncStatusSummary();
415 // Get a description of the sync status for displaying in the user interface.
416 std::string QuerySyncStatusSummaryString();
418 // Initializes a struct of status indicators with data from the backend.
419 // Returns false if the backend was not available for querying; in that case
420 // the struct will be filled with default data.
421 virtual bool QueryDetailedSyncStatus(
422 browser_sync::SyncBackendHost::Status* result);
424 virtual const GoogleServiceAuthError& GetAuthError() const;
426 // Returns true if initial sync setup is in progress (does not return true
427 // if the user is customizing sync after already completing setup once).
428 // ProfileSyncService uses this to determine if it's OK to start syncing, or
429 // if the user is still setting up the initial sync configuration.
430 virtual bool FirstSetupInProgress() const;
432 // Called by the UI to notify the ProfileSyncService that UI is visible so it
433 // will not start syncing. This tells sync whether it's safe to start
434 // downloading data types yet (we don't start syncing until after sync setup
435 // is complete). The UI calls this as soon as any part of the signin wizard is
436 // displayed (even just the login UI).
437 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
438 // that data download starts.
439 virtual void SetSetupInProgress(bool setup_in_progress);
441 // Returns true if the SyncBackendHost has told us it's ready to accept
442 // changes.
443 // [REMARK] - it is safe to call this function only from the ui thread.
444 // because the variable is not thread safe and should only be accessed from
445 // single thread. If we want multiple threads to access this(and there is
446 // currently no need to do so) we need to protect this with a lock.
447 // TODO(timsteele): What happens if the bookmark model is loaded, a change
448 // takes place, and the backend isn't initialized yet?
449 virtual bool sync_initialized() const;
451 virtual bool HasUnrecoverableError() const;
452 const std::string& unrecoverable_error_message() {
453 return unrecoverable_error_message_;
455 tracked_objects::Location unrecoverable_error_location() {
456 return unrecoverable_error_location_;
459 // Returns true if OnPassphraseRequired has been called for decryption and
460 // we have an encrypted data type enabled.
461 virtual bool IsPassphraseRequiredForDecryption() const;
463 syncer::PassphraseRequiredReason passphrase_required_reason() const {
464 return passphrase_required_reason_;
467 // Returns a user-friendly string form of last synced time (in minutes).
468 virtual base::string16 GetLastSyncedTimeString() const;
470 // Returns a human readable string describing backend initialization state.
471 std::string GetBackendInitializationStateString() const;
473 // Returns true if startup is suppressed (i.e. user has stopped syncing via
474 // the google dashboard).
475 virtual bool IsStartSuppressed() const;
477 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
479 // The profile we are syncing for.
480 Profile* profile() const { return profile_; }
482 // Returns a weak pointer to the service's JsController.
483 // Overrideable for testing purposes.
484 virtual base::WeakPtr<syncer::JsController> GetJsController();
486 // Record stats on various events.
487 static void SyncEvent(SyncEventCodes code);
489 // Returns whether sync is enabled. Sync can be enabled/disabled both
490 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
491 // command-line switches).
492 // Profile::IsSyncAccessible() is probably a better signal than this function.
493 // This function can be called from any thread, and the implementation doesn't
494 // assume it's running on the UI thread.
495 static bool IsSyncEnabled();
497 // Returns whether sync is managed, i.e. controlled by configuration
498 // management. If so, the user is not allowed to configure sync.
499 virtual bool IsManaged() const;
501 // syncer::UnrecoverableErrorHandler implementation.
502 virtual void OnUnrecoverableError(
503 const tracked_objects::Location& from_here,
504 const std::string& message) OVERRIDE;
506 // Called when a datatype wishes to disable itself due to having hit an
507 // unrecoverable error.
508 virtual void DisableBrokenDatatype(
509 syncer::ModelType type,
510 const tracked_objects::Location& from_here,
511 std::string message);
513 // The functions below (until ActivateDataType()) should only be
514 // called if sync_initialized() is true.
516 // TODO(akalin): This is called mostly by ModelAssociators and
517 // tests. Figure out how to pass the handle to the ModelAssociators
518 // directly, figure out how to expose this to tests, and remove this
519 // function.
520 virtual syncer::UserShare* GetUserShare() const;
522 // TODO(akalin): These two functions are used only by
523 // ProfileSyncServiceHarness. Figure out a different way to expose
524 // this info to that class, and remove these functions.
526 virtual syncer::sessions::SyncSessionSnapshot
527 GetLastSessionSnapshot() const;
529 // Returns whether or not the underlying sync engine has made any
530 // local changes to items that have not yet been synced with the
531 // server.
532 bool HasUnsyncedItems() const;
534 // Used by ProfileSyncServiceHarness. May return NULL.
535 browser_sync::BackendMigrator* GetBackendMigratorForTest();
537 // Used by tests to inspect interaction with OAuth2TokenService.
538 bool IsRetryingAccessTokenFetchForTest() const;
540 // Used by tests to inspect the OAuth2 access tokens used by PSS.
541 std::string GetAccessTokenForTest() const;
543 // TODO(sync): This is only used in tests. Can we remove it?
544 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
546 // Returns a ListValue indicating the status of all registered types.
548 // The format is:
549 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
550 // where <name> is a type's name, <value> is a string providing details for
551 // the type's status, and <status> is one of "error", "warning" or "ok"
552 // dpending on the type's current status.
554 // This function is used by sync_ui_util.cc to help populate the about:sync
555 // page. It returns a ListValue rather than a DictionaryValue in part to make
556 // it easier to iterate over its elements when constructing that page.
557 base::Value* GetTypeStatusMap() const;
559 // Overridden by tests.
560 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
561 virtual void ActivateDataType(
562 syncer::ModelType type, syncer::ModelSafeGroup group,
563 browser_sync::ChangeProcessor* change_processor);
564 virtual void DeactivateDataType(syncer::ModelType type);
566 // SyncPrefObserver implementation.
567 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
569 // content::NotificationObserver implementation.
570 virtual void Observe(int type,
571 const content::NotificationSource& source,
572 const content::NotificationDetails& details) OVERRIDE;
574 // Changes which data types we're going to be syncing to |preferred_types|.
575 // If it is running, the DataTypeManager will be instructed to reconfigure
576 // the sync backend so that exactly these datatypes are actively synced. See
577 // class comment for more on what it means for a datatype to be Preferred.
578 virtual void ChangePreferredDataTypes(
579 syncer::ModelTypeSet preferred_types);
581 // Returns the set of types which are preferred for enabling. This is a
582 // superset of the active types (see GetActiveDataTypes()).
583 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
585 // Gets the set of all data types that could be allowed (the set that
586 // should be advertised to the user). These will typically only change
587 // via a command-line option. See class comment for more on what it means
588 // for a datatype to be Registered.
589 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
591 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
592 // for sensitive data types. Caller must be holding a
593 // syncapi::BaseTransaction to ensure thread safety.
594 virtual bool IsCryptographerReady(
595 const syncer::BaseTransaction* trans) const;
597 // Returns true if a secondary (explicit) passphrase is being used. It is not
598 // legal to call this method before the backend is initialized.
599 virtual bool IsUsingSecondaryPassphrase() const;
601 // Returns the actual passphrase type being used for encryption.
602 virtual syncer::PassphraseType GetPassphraseType() const;
604 // Returns the time the current explicit passphrase (if any), was set.
605 // If no secondary passphrase is in use, or no time is available, returns an
606 // unset base::Time.
607 virtual base::Time GetExplicitPassphraseTime() const;
609 // Note about setting passphrases: There are different scenarios under which
610 // we might want to apply a passphrase. It could be for first-time encryption,
611 // re-encryption, or for decryption by clients that sign in at a later time.
612 // In addition, encryption can either be done using a custom passphrase, or by
613 // reusing the GAIA password. Depending on what is happening in the system,
614 // callers should determine which of the two methods below must be used.
616 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
617 // specifies whether the passphrase is a custom passphrase or the GAIA
618 // password being reused as a passphrase.
619 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
620 // passphrase with this API.
621 virtual void SetEncryptionPassphrase(const std::string& passphrase,
622 PassphraseType type);
624 // Asynchronously decrypts pending keys using |passphrase|. Returns false
625 // immediately if the passphrase could not be used to decrypt a locally cached
626 // copy of encrypted keys; returns true otherwise.
627 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
628 WARN_UNUSED_RESULT;
630 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
631 // after calling this to force the encryption to occur.
632 virtual void EnableEncryptEverything();
634 // Returns true if we are currently set to encrypt all the sync data. Note:
635 // this is based on the cryptographer's settings, so if the user has recently
636 // requested encryption to be turned on, this may not be true yet. For that,
637 // encryption_pending() must be checked.
638 virtual bool EncryptEverythingEnabled() const;
640 // Returns true if the syncer is waiting for new datatypes to be encrypted.
641 virtual bool encryption_pending() const;
643 const GURL& sync_service_url() const { return sync_service_url_; }
644 bool auto_start_enabled() const { return auto_start_enabled_; }
645 SigninManagerBase* signin() const;
646 bool setup_in_progress() const { return setup_in_progress_; }
648 // Stops the sync backend and sets the flag for suppressing sync startup.
649 void StopAndSuppress();
651 // Resets the flag for suppressing sync startup and starts the sync backend.
652 virtual void UnsuppressAndStart();
654 // Marks all currently registered types as "acknowledged" so we won't prompt
655 // the user about them any more.
656 void AcknowledgeSyncedTypes();
658 SyncGlobalError* sync_global_error() { return sync_global_error_.get(); }
660 // TODO(sync): This is only used in tests. Can we remove it?
661 const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const;
663 browser_sync::DataTypeManager::ConfigureStatus configure_status() {
664 return configure_status_;
667 // If true, the ProfileSyncService has detected that a new GAIA signin has
668 // succeeded, and is waiting for initialization to complete. This is used by
669 // the UI to differentiate between a new auth error (encountered as part of
670 // the initialization process) and a pre-existing auth error that just hasn't
671 // been cleared yet. Virtual for testing purposes.
672 virtual bool waiting_for_auth() const;
674 // The set of currently enabled sync experiments.
675 const syncer::Experiments& current_experiments() const;
677 // OAuth2TokenService::Consumer implementation.
678 virtual void OnGetTokenSuccess(
679 const OAuth2TokenService::Request* request,
680 const std::string& access_token,
681 const base::Time& expiration_time) OVERRIDE;
682 virtual void OnGetTokenFailure(
683 const OAuth2TokenService::Request* request,
684 const GoogleServiceAuthError& error) OVERRIDE;
686 // OAuth2TokenService::Observer implementation.
687 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
688 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
689 virtual void OnRefreshTokensLoaded() OVERRIDE;
691 // BrowserContextKeyedService implementation. This must be called exactly
692 // once (before this object is destroyed).
693 virtual void Shutdown() OVERRIDE;
695 // Called when a datatype (SyncableService) has a need for sync to start
696 // ASAP, presumably because a local change event has occurred but we're
697 // still in deferred start mode, meaning the SyncableService hasn't been
698 // told to MergeDataAndStartSyncing yet.
699 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
701 // Return sync token status.
702 SyncTokenStatus GetSyncTokenStatus() const;
704 browser_sync::FaviconCache* GetFaviconCache();
706 // Overrides the NetworkResources used for Sync connections.
707 // This function takes ownership of |network_resources|.
708 void OverrideNetworkResourcesForTest(
709 scoped_ptr<syncer::NetworkResources> network_resources);
711 virtual bool IsSessionsDataTypeControllerRunning() const;
713 protected:
714 // Helper to configure the priority data types.
715 void ConfigurePriorityDataTypes();
717 // Helper to install and configure a data type manager.
718 void ConfigureDataTypeManager();
720 // Shuts down the backend sync components.
721 // |option| indicates if syncing is being disabled or not, and whether
722 // to claim ownership of sync thread from backend.
723 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option);
725 // Return SyncCredentials from the OAuth2TokenService.
726 syncer::SyncCredentials GetCredentials();
728 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
730 const browser_sync::DataTypeController::TypeMap& data_type_controllers() {
731 return data_type_controllers_;
734 // Helper method for managing encryption UI.
735 bool IsEncryptedDatatypeEnabled() const;
737 // Helper for OnUnrecoverableError.
738 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
739 // and in SyncBackendHost::Shutdown.
740 void OnUnrecoverableErrorImpl(
741 const tracked_objects::Location& from_here,
742 const std::string& message,
743 bool delete_sync_database);
745 // This is a cache of the last authentication response we received from the
746 // sync server. The UI queries this to display appropriate messaging to the
747 // user.
748 GoogleServiceAuthError last_auth_error_;
750 // Our asynchronous backend to communicate with sync components living on
751 // other threads.
752 scoped_ptr<browser_sync::SyncBackendHost> backend_;
754 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
755 // was required for encryption, decryption with a cached passphrase, or
756 // because a new passphrase is required?
757 syncer::PassphraseRequiredReason passphrase_required_reason_;
759 private:
760 enum UnrecoverableErrorReason {
761 ERROR_REASON_UNSET,
762 ERROR_REASON_SYNCER,
763 ERROR_REASON_BACKEND_INIT_FAILURE,
764 ERROR_REASON_CONFIGURATION_RETRY,
765 ERROR_REASON_CONFIGURATION_FAILURE,
766 ERROR_REASON_ACTIONABLE_ERROR,
767 ERROR_REASON_LIMIT
770 enum AuthErrorMetric {
771 AUTH_ERROR_ENCOUNTERED,
772 AUTH_ERROR_FIXED,
773 AUTH_ERROR_LIMIT
776 friend class ProfileSyncServicePasswordTest;
777 friend class SyncTest;
778 friend class TestProfileSyncService;
779 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
781 // Update the last auth error and notify observers of error state.
782 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
784 // Detects and attempts to recover from a previous improper datatype
785 // configuration where Keep Everything Synced and the preferred types were
786 // not correctly set.
787 void TrySyncDatatypePrefRecovery();
789 // Starts up sync if it is not suppressed and preconditions are met.
790 // Called from Initialize() and UnsuppressAndStart().
791 void TryStart();
793 // Puts the backend's sync scheduler into NORMAL mode.
794 // Called when configuration is complete.
795 void StartSyncingWithServer();
797 // Called when we've determined that we don't need a passphrase (either
798 // because OnPassphraseAccepted() was called, or because we've gotten a
799 // OnPassphraseRequired() but no data types are enabled).
800 void ResolvePassphraseRequired();
802 // During initial signin, ProfileSyncService caches the user's signin
803 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
804 // This routine is invoked once the backend has started up to use the
805 // cached passphrase and clear it out when it is done.
806 void ConsumeCachedPassphraseIfPossible();
808 // RequestAccessToken initiates RPC to request downscoped access token from
809 // refresh token. This happens when a new OAuth2 login token is loaded and
810 // when sync server returns AUTH_ERROR which indicates it is time to refresh
811 // token.
812 virtual void RequestAccessToken();
814 // If |delete_sync_data_folder| is true, then this method will delete all
815 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
816 void InitializeBackend(bool delete_sync_data_folder);
818 // Initializes the various settings from the command line.
819 void InitSettings();
821 // Sets the last synced time to the current time.
822 void UpdateLastSyncedTime();
824 void NotifyObservers();
825 void NotifySyncCycleCompleted();
827 void ClearStaleErrors();
829 void ClearUnrecoverableError();
831 enum StartUpDeferredOption {
832 STARTUP_BACKEND_DEFERRED,
833 STARTUP_IMMEDIATE
835 void StartUp(StartUpDeferredOption deferred_option);
837 // Starts up the backend sync components.
838 void StartUpSlowBackendComponents();
840 // About-flags experiment names for datatypes that aren't enabled by default
841 // yet.
842 static std::string GetExperimentNameForDataType(
843 syncer::ModelType data_type);
845 // Create and register a new datatype controller.
846 void RegisterNewDataType(syncer::ModelType data_type);
848 // Reconfigures the data type manager with the latest enabled types.
849 // Note: Does not initialize the backend if it is not already initialized.
850 // This function needs to be called only after sync has been initialized
851 // (i.e.,only for reconfigurations). The reason we don't initialize the
852 // backend is because if we had encountered an unrecoverable error we don't
853 // want to startup once more.
854 virtual void ReconfigureDatatypeManager();
856 // Called when the user changes the sync configuration, to update the UMA
857 // stats.
858 void UpdateSelectedTypesHistogram(
859 bool sync_everything,
860 const syncer::ModelTypeSet chosen_types) const;
862 #if defined(OS_CHROMEOS)
863 // Refresh spare sync bootstrap token for re-enabling the sync service.
864 // Called on successful sign-in notifications.
865 void RefreshSpareBootstrapToken(const std::string& passphrase);
866 #endif
868 // Internal unrecoverable error handler. Used to track error reason via
869 // Sync.UnrecoverableErrors histogram.
870 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
871 const std::string& message,
872 bool delete_sync_database,
873 UnrecoverableErrorReason reason);
875 // Returns the username (in form of an email address) that should be used in
876 // the credentials.
877 std::string GetEffectiveUsername();
879 // Returns the account ID to use to get tokens.
880 std::string GetAccountIdToUse();
882 // Factory used to create various dependent objects.
883 scoped_ptr<ProfileSyncComponentsFactory> factory_;
885 // The profile whose data we are synchronizing.
886 Profile* profile_;
888 // The class that handles getting, setting, and persisting sync
889 // preferences.
890 browser_sync::SyncPrefs sync_prefs_;
892 // TODO(ncarter): Put this in a profile, once there is UI for it.
893 // This specifies where to find the sync server.
894 GURL sync_service_url_;
896 // The last time we detected a successful transition from SYNCING state.
897 // Our backend notifies us whenever we should take a new snapshot.
898 base::Time last_synced_time_;
900 // The time that StartUp() is called. This member is zero if StartUp() has
901 // never been called, and is reset to zero once OnBackendInitialized() is
902 // called.
903 base::Time start_up_time_;
905 // Whether we have received a signal from a SyncableService requesting that
906 // sync starts as soon as possible.
907 // TODO(tim): Move this and other TryStart related logic + state to separate
908 // class. Bug 80149.
909 bool data_type_requested_sync_startup_;
911 // The time that OnConfigureStart is called. This member is zero if
912 // OnConfigureStart has not yet been called, and is reset to zero once
913 // OnConfigureDone is called.
914 base::Time sync_configure_start_time_;
916 // Indicates if this is the first time sync is being configured. This value
917 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
918 bool is_first_time_sync_configure_;
920 // List of available data type controllers.
921 browser_sync::DataTypeController::TypeMap data_type_controllers_;
923 // Whether the SyncBackendHost has been initialized.
924 bool backend_initialized_;
926 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
927 // ProfileSyncService from starting backend till browser restarted or user
928 // signed out.
929 bool sync_disabled_by_admin_;
931 // Set to true if a signin has completed but we're still waiting for the
932 // backend to refresh its credentials.
933 bool is_auth_in_progress_;
935 // Encapsulates user signin - used to set/get the user's authenticated
936 // email address.
937 scoped_ptr<ManagedUserSigninManagerWrapper> signin_;
939 // Information describing an unrecoverable error.
940 UnrecoverableErrorReason unrecoverable_error_reason_;
941 std::string unrecoverable_error_message_;
942 tracked_objects::Location unrecoverable_error_location_;
944 // Manages the start and stop of the various data types.
945 scoped_ptr<browser_sync::DataTypeManager> data_type_manager_;
947 ObserverList<ProfileSyncServiceBase::Observer> observers_;
949 syncer::SyncJsController sync_js_controller_;
951 content::NotificationRegistrar registrar_;
953 // This allows us to gracefully handle an ABORTED return code from the
954 // DataTypeManager in the event that the server informed us to cease and
955 // desist syncing immediately.
956 bool expect_sync_configuration_aborted_;
958 // Sometimes we need to temporarily hold on to a passphrase because we don't
959 // yet have a backend to send it to. This happens during initialization as
960 // we don't StartUp until we have a valid token, which happens after valid
961 // credentials were provided.
962 std::string cached_passphrase_;
964 // The current set of encrypted types. Always a superset of
965 // syncer::Cryptographer::SensitiveTypes().
966 syncer::ModelTypeSet encrypted_types_;
968 // Whether we want to encrypt everything.
969 bool encrypt_everything_;
971 // Whether we're waiting for an attempt to encryption all sync data to
972 // complete. We track this at this layer in order to allow the user to cancel
973 // if they e.g. don't remember their explicit passphrase.
974 bool encryption_pending_;
976 // If true, we want to automatically start sync signin whenever we have
977 // credentials (user doesn't need to go through the startup flow). This is
978 // typically enabled on platforms (like ChromeOS) that have their own
979 // distinct signin flow.
980 const bool auto_start_enabled_;
982 scoped_ptr<browser_sync::BackendMigrator> migrator_;
984 // This is the last |SyncProtocolError| we received from the server that had
985 // an action set on it.
986 syncer::SyncProtocolError last_actionable_error_;
988 // This is used to show sync errors in the wrench menu.
989 scoped_ptr<SyncGlobalError> sync_global_error_;
991 // Tracks the set of failed data types (those that encounter an error
992 // or must delay loading for some reason).
993 browser_sync::FailedDataTypesHandler failed_data_types_handler_;
995 browser_sync::DataTypeManager::ConfigureStatus configure_status_;
997 // If |true|, there is setup UI visible so we should not start downloading
998 // data types.
999 bool setup_in_progress_;
1001 // The set of currently enabled sync experiments.
1002 syncer::Experiments current_experiments_;
1004 // Sync's internal debug info listener. Used to record datatype configuration
1005 // and association information.
1006 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1008 // A thread where all the sync operations happen.
1009 // OWNERSHIP Notes:
1010 // * Created when backend starts for the first time.
1011 // * If sync is disabled, PSS claims ownership from backend.
1012 // * If sync is reenabled, PSS passes ownership to new backend.
1013 scoped_ptr<base::Thread> sync_thread_;
1015 // ProfileSyncService uses this service to get access tokens.
1016 ProfileOAuth2TokenService* oauth2_token_service_;
1018 // ProfileSyncService needs to remember access token in order to invalidate it
1019 // with OAuth2TokenService.
1020 std::string access_token_;
1022 // ProfileSyncService needs to hold reference to access_token_request_ for
1023 // the duration of request in order to receive callbacks.
1024 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1026 // If RequestAccessToken fails with transient error then retry requesting
1027 // access token with exponential backoff.
1028 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1029 net::BackoffEntry request_access_token_backoff_;
1031 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1033 // States related to sync token and connection.
1034 base::Time connection_status_update_time_;
1035 syncer::ConnectionStatus connection_status_;
1036 base::Time token_request_time_;
1037 base::Time token_receive_time_;
1038 GoogleServiceAuthError last_get_token_error_;
1039 base::Time next_token_request_time_;
1041 scoped_ptr<SessionsSyncManager> sessions_sync_manager_;
1043 scoped_ptr<syncer::NetworkResources> network_resources_;
1045 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1048 bool ShouldShowActionOnUI(
1049 const syncer::SyncProtocolError& error);
1052 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_