- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / sync / profile_sync_service.h
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.
4
5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_
7
8 #include <string>
9 #include <utility>
10 #include <vector>
11
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"
48 #include "url/gurl.h"
49
50 class ProfileOAuth2TokenService;
51 class Profile;
52 class ProfileSyncComponentsFactory;
53 class SigninManagerBase;
54 class SyncGlobalError;
55
56 namespace browser_sync {
57 class BackendMigrator;
58 class ChangeProcessor;
59 class DataTypeManager;
60 class DeviceInfo;
61 class JsController;
62 class SessionModelAssociator;
63
64 namespace sessions {
65 class SyncSessionSnapshot;
66 }  // namespace sessions
67 }  // namespace browser_sync
68
69 namespace syncer {
70 class BaseTransaction;
71 struct SyncCredentials;
72 struct UserShare;
73 }  // namespace syncer
74
75 namespace sync_pb {
76 class EncryptedData;
77 }  // namespace sync_pb
78
79 // ProfileSyncService is the layer between browser subsystems like bookmarks,
80 // and the sync backend.  Each subsystem is logically thought of as being
81 // a sync datatype.
82 //
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:
85 //
86 //   'Registered' (feature suppression for a datatype)
87 //
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
91 //      synced.
92 //
93 //      A datatype is considered registered once RegisterDataTypeController
94 //      has been called with that datatype's DataTypeController.
95 //
96 //   'Preferred' (user preferences and opt-out for a datatype)
97 //
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.
102 //
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.
107 //
108 //   'Active' (run-time initialization of sync system for a datatype)
109 //
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
115 //      as necessary.
116 //
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.
120 //
121 // Sync Configuration:
122 //
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
128 //        passphrase.
129 //
130 //   Additionally, the current sync configuration can be fetched by calling
131 //    * GetRegisteredDataTypes()
132 //    * GetPreferredDataTypes()
133 //    * GetActiveDataTypes()
134 //    * IsUsingSecondaryPassphrase()
135 //    * EncryptEverythingEnabled()
136 //    * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
137 //
138 //   The "sync everything" state cannot be read from ProfileSyncService, but
139 //   is instead pulled from SyncPrefs.HasKeepEverythingSynced().
140 //
141 // Initial sync setup:
142 //
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:
146 //
147 //    * SetSyncSetupCompleted()
148 //    * SetSetupInProgress()
149 //
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.
156 //
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.
161 //
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 {
173  public:
174   typedef browser_sync::SyncBackendHost::Status Status;
175
176   enum SyncEventCodes  {
177     MIN_SYNC_EVENT_CODE = 0,
178
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.
186
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.
196
197     // Miscellaneous events caused by sync service.
198
199     MAX_SYNC_EVENT_CODE
200   };
201
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().
209   enum StartBehavior {
210     AUTO_START,
211     MANUAL_START,
212   };
213
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.
220   };
221
222   enum SyncStatusSummary {
223     UNRECOVERABLE_ERROR,
224     NOT_ENABLED,
225     SETUP_INCOMPLETE,
226     DATATYPES_NOT_INITIALIZED,
227     INITIALIZED,
228     UNKNOWN_ERROR,
229   };
230
231   // Default sync server URL.
232   static const char* kSyncServerUrl;
233   // Sync server URL for dev channel users
234   static const char* kDevServerUrl;
235
236   // Takes ownership of |factory|.
237   ProfileSyncService(ProfileSyncComponentsFactory* factory,
238                      Profile* profile,
239                      SigninManagerBase* signin,
240                      ProfileOAuth2TokenService* oauth2_token_service,
241                      StartBehavior start_behavior);
242   virtual ~ProfileSyncService();
243
244   // Initializes the object. This must be called at most once, and
245   // immediately after an object of this class is constructed.
246   void Initialize();
247
248   virtual void SetSyncSetupCompleted();
249
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;
259
260   void RegisterAuthNotifications();
261   void UnregisterAuthNotifications();
262
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();
269
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();
273
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);
280
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
283   // null.
284   // TODO(zea): Figure out a better way to expose this to the UI elements that
285   // need it.
286   virtual browser_sync::SessionModelAssociator* GetSessionModelAssociator();
287
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;
291
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
294   // is unavailable.
295   virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
296       const std::string& client_id) const;
297
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;
301
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
305   // initialized.
306   virtual std::string GetLocalDeviceGUID() const;
307
308   // Notifies the observer of any device info changes.
309   virtual void AddObserverForDeviceInfoChange(
310       browser_sync::SyncedDeviceTracker::Observer* observer);
311
312   // Removes the observer from device info notification.
313   virtual void RemoveObserverForDeviceInfoChange(
314       browser_sync::SyncedDeviceTracker::Observer* observer);
315
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;
320
321   // Disables sync for user. Use ShowLoginDialog to enable.
322   virtual void DisableForUser();
323
324   // SyncFrontend implementation.
325   virtual void OnBackendInitialized(
326       const syncer::WeakHandle<syncer::JsBackend>& js_backend,
327       const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
328           debug_info_listener,
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;
349
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;
355
356   // DataTypeEncryptionHandler implementation.
357   virtual bool IsPassphraseRequired() const OVERRIDE;
358   virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
359
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);
367
368   // Get the sync status code.
369   SyncStatusSummary QuerySyncStatusSummary();
370
371   // Get a description of the sync status for displaying in the user interface.
372   std::string QuerySyncStatusSummaryString();
373
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);
379
380   virtual const GoogleServiceAuthError& GetAuthError() const;
381
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;
387
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);
396
397   // Returns true if the SyncBackendHost has told us it's ready to accept
398   // changes.
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;
406
407   virtual bool HasUnrecoverableError() const;
408   const std::string& unrecoverable_error_message() {
409     return unrecoverable_error_message_;
410   }
411   tracked_objects::Location unrecoverable_error_location() {
412     return unrecoverable_error_location_;
413   }
414
415   // Returns true if OnPassphraseRequired has been called for decryption and
416   // we have an encrypted data type enabled.
417   virtual bool IsPassphraseRequiredForDecryption() const;
418
419   syncer::PassphraseRequiredReason passphrase_required_reason() const {
420     return passphrase_required_reason_;
421   }
422
423   // Returns a user-friendly string form of last synced time (in minutes).
424   virtual string16 GetLastSyncedTimeString() const;
425
426   // Returns a human readable string describing backend initialization state.
427   std::string GetBackendInitializationStateString() const;
428
429   // Returns true if startup is suppressed (i.e. user has stopped syncing via
430   // the google dashboard).
431   virtual bool IsStartSuppressed() const;
432
433   ProfileSyncComponentsFactory* factory() { return factory_.get(); }
434
435   // The profile we are syncing for.
436   Profile* profile() const { return profile_; }
437
438   // Returns a weak pointer to the service's JsController.
439   // Overrideable for testing purposes.
440   virtual base::WeakPtr<syncer::JsController> GetJsController();
441
442   // Record stats on various events.
443   static void SyncEvent(SyncEventCodes code);
444
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();
452
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;
456
457   // SigninGlobalError::AuthStatusProvider implementation.
458   virtual std::string GetAccountId() const OVERRIDE;
459   virtual GoogleServiceAuthError GetAuthStatus() const OVERRIDE;
460
461   // syncer::UnrecoverableErrorHandler implementation.
462   virtual void OnUnrecoverableError(
463       const tracked_objects::Location& from_here,
464       const std::string& message) OVERRIDE;
465
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);
472
473   // The functions below (until ActivateDataType()) should only be
474   // called if sync_initialized() is true.
475
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
479   // function.
480   virtual syncer::UserShare* GetUserShare() const;
481
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.
485
486   virtual syncer::sessions::SyncSessionSnapshot
487       GetLastSessionSnapshot() const;
488
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
491   // server.
492   bool HasUnsyncedItems() const;
493
494   // Used by ProfileSyncServiceHarness.  May return NULL.
495   browser_sync::BackendMigrator* GetBackendMigratorForTest();
496
497   // TODO(sync): This is only used in tests.  Can we remove it?
498   void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
499
500   // Returns a ListValue indicating the status of all registered types.
501   //
502   // The format is:
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.
507   //
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;
512
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);
519
520   // SyncPrefObserver implementation.
521   virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
522
523   // content::NotificationObserver implementation.
524   virtual void Observe(int type,
525                        const content::NotificationSource& source,
526                        const content::NotificationDetails& details) OVERRIDE;
527
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);
534
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;
538
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;
544
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;
550
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;
554
555   // Returns the actual passphrase type being used for encryption.
556   virtual syncer::PassphraseType GetPassphraseType() const;
557
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
560   // unset base::Time.
561   virtual base::Time GetExplicitPassphraseTime() const;
562
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.
569
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);
577
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)
582       WARN_UNUSED_RESULT;
583
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();
587
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;
593
594   // Returns true if the syncer is waiting for new datatypes to be encrypted.
595   virtual bool encryption_pending() const;
596
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_; }
601
602   // Stops the sync backend and sets the flag for suppressing sync startup.
603   void StopAndSuppress();
604
605   // Resets the flag for suppressing sync startup and starts the sync backend.
606   virtual void UnsuppressAndStart();
607
608   // Marks all currently registered types as "acknowledged" so we won't prompt
609   // the user about them any more.
610   void AcknowledgeSyncedTypes();
611
612   SyncGlobalError* sync_global_error() { return sync_global_error_.get(); }
613
614   // TODO(sync): This is only used in tests.  Can we remove it?
615   const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const;
616
617   browser_sync::DataTypeManager::ConfigureStatus configure_status() {
618     return configure_status_;
619   }
620
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;
627
628   // The set of currently enabled sync experiments.
629   const syncer::Experiments& current_experiments() const;
630
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;
639
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;
644
645   // BrowserContextKeyedService implementation.  This must be called exactly
646   // once (before this object is destroyed).
647   virtual void Shutdown() OVERRIDE;
648
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);
654
655  protected:
656   // Used by test classes that derive from ProfileSyncService.
657   virtual browser_sync::SyncBackendHost* GetBackendForTest();
658
659   // Helper to configure the priority data types.
660   void ConfigurePriorityDataTypes();
661
662   // Helper to install and configure a data type manager.
663   void ConfigureDataTypeManager();
664
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);
669
670   // Return SyncCredentials from the TokenService.
671   syncer::SyncCredentials GetCredentials();
672
673   virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
674
675   // Test need to override this to create backends that allow setting up
676   // initial conditions, such as populating sync nodes.
677   //
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();
682
683   const browser_sync::DataTypeController::TypeMap& data_type_controllers() {
684     return data_type_controllers_;
685   }
686
687   // Helper method for managing encryption UI.
688   bool IsEncryptedDatatypeEnabled() const;
689
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);
697
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
700   // user.
701   GoogleServiceAuthError last_auth_error_;
702
703   // Our asynchronous backend to communicate with sync components living on
704   // other threads.
705   scoped_ptr<browser_sync::SyncBackendHost> backend_;
706
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_;
711
712  private:
713   enum UnrecoverableErrorReason {
714     ERROR_REASON_UNSET,
715     ERROR_REASON_SYNCER,
716     ERROR_REASON_BACKEND_INIT_FAILURE,
717     ERROR_REASON_CONFIGURATION_RETRY,
718     ERROR_REASON_CONFIGURATION_FAILURE,
719     ERROR_REASON_ACTIONABLE_ERROR,
720     ERROR_REASON_LIMIT
721   };
722   friend class ProfileSyncServicePasswordTest;
723   friend class SyncTest;
724   friend class TestProfileSyncService;
725   FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
726
727   // Update the last auth error and notify observers of error state.
728   void UpdateAuthErrorState(const GoogleServiceAuthError& error);
729
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();
734
735   // Starts up sync if it is not suppressed and preconditions are met.
736   // Called from Initialize() and UnsuppressAndStart().
737   void TryStart();
738
739   // Puts the backend's sync scheduler into NORMAL mode.
740   // Called when configuration is complete.
741   void StartSyncingWithServer();
742
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();
747
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();
753
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
757   // token.
758   virtual void RequestAccessToken();
759
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);
763
764   // Initializes the various settings from the command line.
765   void InitSettings();
766
767   // Sets the last synced time to the current time.
768   void UpdateLastSyncedTime();
769
770   void NotifyObservers();
771   void NotifySyncCycleCompleted();
772
773   void ClearStaleErrors();
774
775   void ClearUnrecoverableError();
776
777   enum StartUpDeferredOption {
778     STARTUP_BACKEND_DEFERRED,
779     STARTUP_IMMEDIATE
780   };
781   void StartUp(StartUpDeferredOption deferred_option);
782
783   // Starts up the backend sync components.
784   void StartUpSlowBackendComponents();
785
786   // About-flags experiment names for datatypes that aren't enabled by default
787   // yet.
788   static std::string GetExperimentNameForDataType(
789       syncer::ModelType data_type);
790
791   // Create and register a new datatype controller.
792   void RegisterNewDataType(syncer::ModelType data_type);
793
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();
801
802   // Called when the user changes the sync configuration, to update the UMA
803   // stats.
804   void UpdateSelectedTypesHistogram(
805       bool sync_everything,
806       const syncer::ModelTypeSet chosen_types) const;
807
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);
812 #endif
813
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);
820
821   // Returns the username (in form of an email address) that should be used in
822   // the credentials.
823   std::string GetEffectiveUsername();
824
825  // Factory used to create various dependent objects.
826   scoped_ptr<ProfileSyncComponentsFactory> factory_;
827
828   // The profile whose data we are synchronizing.
829   Profile* profile_;
830
831   // The class that handles getting, setting, and persisting sync
832   // preferences.
833   browser_sync::SyncPrefs sync_prefs_;
834
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_;
838
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_;
842
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
845   // called.
846   base::Time start_up_time_;
847
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
851   // class. Bug 80149.
852   bool data_type_requested_sync_startup_;
853
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_;
858
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_;
862
863   // List of available data type controllers.
864   browser_sync::DataTypeController::TypeMap data_type_controllers_;
865
866   // Whether the SyncBackendHost has been initialized.
867   bool backend_initialized_;
868
869   // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
870   // ProfileSyncService from starting backend till browser restarted or user
871   // signed out.
872   bool sync_disabled_by_admin_;
873
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_;
877
878   // Encapsulates user signin - used to set/get the user's authenticated
879   // email address.
880   SigninManagerBase* signin_;
881
882   // Information describing an unrecoverable error.
883   UnrecoverableErrorReason unrecoverable_error_reason_;
884   std::string unrecoverable_error_message_;
885   tracked_objects::Location unrecoverable_error_location_;
886
887   // Manages the start and stop of the various data types.
888   scoped_ptr<browser_sync::DataTypeManager> data_type_manager_;
889
890   ObserverList<ProfileSyncServiceBase::Observer> observers_;
891
892   syncer::SyncJsController sync_js_controller_;
893
894   content::NotificationRegistrar registrar_;
895
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_;
900
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_;
906
907   // The current set of encrypted types.  Always a superset of
908   // syncer::Cryptographer::SensitiveTypes().
909   syncer::ModelTypeSet encrypted_types_;
910
911   // Whether we want to encrypt everything.
912   bool encrypt_everything_;
913
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_;
918
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_;
924
925   scoped_ptr<browser_sync::BackendMigrator> migrator_;
926
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_;
930
931   // This is used to show sync errors in the wrench menu.
932   scoped_ptr<SyncGlobalError> sync_global_error_;
933
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_;
937
938   browser_sync::DataTypeManager::ConfigureStatus configure_status_;
939
940   // If |true|, there is setup UI visible so we should not start downloading
941   // data types.
942   bool setup_in_progress_;
943
944   // The set of currently enabled sync experiments.
945   syncer::Experiments current_experiments_;
946
947   // Sync's internal debug info listener. Used to record datatype configuration
948   // and association information.
949   syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
950
951   // A thread where all the sync operations happen.
952   // OWNERSHIP Notes:
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_;
957
958   // ProfileSyncService uses this service to get access tokens.
959   ProfileOAuth2TokenService* oauth2_token_service_;
960
961   // ProfileSyncService needs to remember access token in order to invalidate it
962   // with OAuth2TokenService.
963   std::string access_token_;
964
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_;
968
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_;
973
974   base::WeakPtrFactory<ProfileSyncService> weak_factory_;
975
976   DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
977 };
978
979 bool ShouldShowActionOnUI(
980     const syncer::SyncProtocolError& error);
981
982
983 #endif  // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_