0325d0d15e98ca71acfc5c7e34f99677a1b3a8ed
[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/sync/backend_unrecoverable_error_handler.h"
24 #include "chrome/browser/sync/backup_rollback_controller.h"
25 #include "chrome/browser/sync/glue/sync_backend_host.h"
26 #include "chrome/browser/sync/glue/synced_device_tracker.h"
27 #include "chrome/browser/sync/profile_sync_service_base.h"
28 #include "chrome/browser/sync/profile_sync_service_observer.h"
29 #include "chrome/browser/sync/protocol_event_observer.h"
30 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
31 #include "chrome/browser/sync/startup_controller.h"
32 #include "components/keyed_service/core/keyed_service.h"
33 #include "components/signin/core/browser/signin_manager_base.h"
34 #include "components/sync_driver/data_type_controller.h"
35 #include "components/sync_driver/data_type_encryption_handler.h"
36 #include "components/sync_driver/data_type_manager.h"
37 #include "components/sync_driver/data_type_manager_observer.h"
38 #include "components/sync_driver/failed_data_types_handler.h"
39 #include "components/sync_driver/non_blocking_data_type_manager.h"
40 #include "components/sync_driver/sync_frontend.h"
41 #include "components/sync_driver/sync_prefs.h"
42 #include "google_apis/gaia/google_service_auth_error.h"
43 #include "google_apis/gaia/oauth2_token_service.h"
44 #include "net/base/backoff_entry.h"
45 #include "sync/internal_api/public/base/model_type.h"
46 #include "sync/internal_api/public/engine/model_safe_worker.h"
47 #include "sync/internal_api/public/sync_manager_factory.h"
48 #include "sync/internal_api/public/util/experiments.h"
49 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
50 #include "sync/js/sync_js_controller.h"
51 #include "url/gurl.h"
52
53 class ManagedUserSigninManagerWrapper;
54 class Profile;
55 class ProfileOAuth2TokenService;
56 class ProfileSyncComponentsFactory;
57 class SyncErrorController;
58
59 namespace base {
60 class CommandLine;
61 };
62
63 namespace browser_sync {
64 class BackendMigrator;
65 class ChangeProcessor;
66 class DataTypeManager;
67 class DeviceInfo;
68 class FaviconCache;
69 class JsController;
70 class OpenTabsUIDelegate;
71
72 namespace sessions {
73 class SyncSessionSnapshot;
74 }  // namespace sessions
75 }  // namespace browser_sync
76
77 namespace syncer {
78 class BaseTransaction;
79 class NetworkResources;
80 struct CommitCounters;
81 struct StatusCounters;
82 struct SyncCredentials;
83 struct UpdateCounters;
84 struct UserShare;
85 }  // namespace syncer
86
87 namespace sync_pb {
88 class EncryptedData;
89 }  // namespace sync_pb
90
91 using browser_sync::SessionsSyncManager;
92
93 // ProfileSyncService is the layer between browser subsystems like bookmarks,
94 // and the sync backend.  Each subsystem is logically thought of as being
95 // a sync datatype.
96 //
97 // Individual datatypes can, at any point, be in a variety of stages of being
98 // "enabled".  Here are some specific terms for concepts used in this class:
99 //
100 //   'Registered' (feature suppression for a datatype)
101 //
102 //      When a datatype is registered, the user has the option of syncing it.
103 //      The sync opt-in UI will show only registered types; a checkbox should
104 //      never be shown for an unregistered type, and nor should it ever be
105 //      synced.
106 //
107 //      A datatype is considered registered once RegisterDataTypeController
108 //      has been called with that datatype's DataTypeController.
109 //
110 //   'Preferred' (user preferences and opt-out for a datatype)
111 //
112 //      This means the user's opt-in or opt-out preference on a per-datatype
113 //      basis.  The sync service will try to make active exactly these types.
114 //      If a user has opted out of syncing a particular datatype, it will
115 //      be registered, but not preferred.
116 //
117 //      This state is controlled by the ConfigurePreferredDataTypes and
118 //      GetPreferredDataTypes.  They are stored in the preferences system,
119 //      and persist; though if a datatype is not registered, it cannot
120 //      be a preferred datatype.
121 //
122 //   'Active' (run-time initialization of sync system for a datatype)
123 //
124 //      An active datatype is a preferred datatype that is actively being
125 //      synchronized: the syncer has been instructed to querying the server
126 //      for this datatype, first-time merges have finished, and there is an
127 //      actively installed ChangeProcessor that listens for changes to this
128 //      datatype, propagating such changes into and out of the sync backend
129 //      as necessary.
130 //
131 //      When a datatype is in the process of becoming active, it may be
132 //      in some intermediate state.  Those finer-grained intermediate states
133 //      are differentiated by the DataTypeController state.
134 //
135 // Sync Configuration:
136 //
137 //   Sync configuration is accomplished via the following APIs:
138 //    * OnUserChoseDatatypes(): Set the data types the user wants to sync.
139 //    * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
140 //        using the passed passphrase.
141 //    * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
142 //        passphrase.
143 //
144 //   Additionally, the current sync configuration can be fetched by calling
145 //    * GetRegisteredDataTypes()
146 //    * GetPreferredDataTypes()
147 //    * GetActiveDataTypes()
148 //    * IsUsingSecondaryPassphrase()
149 //    * EncryptEverythingEnabled()
150 //    * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
151 //
152 //   The "sync everything" state cannot be read from ProfileSyncService, but
153 //   is instead pulled from SyncPrefs.HasKeepEverythingSynced().
154 //
155 // Initial sync setup:
156 //
157 //   For privacy reasons, it is usually desirable to avoid syncing any data
158 //   types until the user has finished setting up sync. There are two APIs
159 //   that control the initial sync download:
160 //
161 //    * SetSyncSetupCompleted()
162 //    * SetSetupInProgress()
163 //
164 //   SetSyncSetupCompleted() should be called once the user has finished setting
165 //   up sync at least once on their account. SetSetupInProgress(true) should be
166 //   called while the user is actively configuring their account, and then
167 //   SetSetupInProgress(false) should be called when configuration is complete.
168 //   When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
169 //   been called, then the sync engine knows not to download any user data.
170 //
171 //   When initial sync is complete, the UI code should call
172 //   SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
173 //   tell the sync engine that setup is completed and it can begin downloading
174 //   data from the sync server.
175 //
176 class ProfileSyncService : public ProfileSyncServiceBase,
177                            public browser_sync::SyncFrontend,
178                            public sync_driver::SyncPrefObserver,
179                            public browser_sync::DataTypeManagerObserver,
180                            public syncer::UnrecoverableErrorHandler,
181                            public KeyedService,
182                            public browser_sync::DataTypeEncryptionHandler,
183                            public OAuth2TokenService::Consumer,
184                            public OAuth2TokenService::Observer,
185                            public SessionsSyncManager::SyncInternalApiDelegate,
186                            public SigninManagerBase::Observer {
187  public:
188   typedef browser_sync::SyncBackendHost::Status Status;
189
190   // Status of sync server connection, sync token and token request.
191   struct SyncTokenStatus {
192     SyncTokenStatus();
193     ~SyncTokenStatus();
194
195     // Sync server connection status reported by sync backend.
196     base::Time connection_status_update_time;
197     syncer::ConnectionStatus connection_status;
198
199     // Times when OAuth2 access token is requested and received.
200     base::Time token_request_time;
201     base::Time token_receive_time;
202
203     // Error returned by OAuth2TokenService for token request and time when
204     // next request is scheduled.
205     GoogleServiceAuthError last_get_token_error;
206     base::Time next_token_request_time;
207   };
208
209   enum SyncEventCodes  {
210     MIN_SYNC_EVENT_CODE = 0,
211
212     // Events starting the sync service.
213     START_FROM_NTP = 1,      // Sync was started from the ad in NTP
214     START_FROM_WRENCH = 2,   // Sync was started from the Wrench menu.
215     START_FROM_OPTIONS = 3,  // Sync was started from Wrench->Options.
216     START_FROM_BOOKMARK_MANAGER = 4,  // Sync was started from Bookmark manager.
217     START_FROM_PROFILE_MENU = 5,  // Sync was started from multiprofile menu.
218     START_FROM_URL = 6,  // Sync was started from a typed URL.
219
220     // Events regarding cancellation of the signon process of sync.
221     CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10,   // Cancelled before submitting
222                                             // username and password.
223     CANCEL_DURING_SIGNON = 11,              // Cancelled after auth.
224     CANCEL_DURING_CONFIGURE = 12,           // Cancelled before choosing data
225                                             // types and clicking OK.
226     // Events resulting in the stoppage of sync service.
227     STOP_FROM_OPTIONS = 20,  // Sync was stopped from Wrench->Options.
228     STOP_FROM_ADVANCED_DIALOG = 21,  // Sync was stopped via advanced settings.
229
230     // Miscellaneous events caused by sync service.
231
232     MAX_SYNC_EVENT_CODE
233   };
234
235   // Used to specify the kind of passphrase with which sync data is encrypted.
236   enum PassphraseType {
237     IMPLICIT,  // The user did not provide a custom passphrase for encryption.
238                // We implicitly use the GAIA password in such cases.
239     EXPLICIT,  // The user selected the "use custom passphrase" radio button
240                // during sync setup and provided a passphrase.
241   };
242
243   enum SyncStatusSummary {
244     UNRECOVERABLE_ERROR,
245     NOT_ENABLED,
246     SETUP_INCOMPLETE,
247     DATATYPES_NOT_INITIALIZED,
248     INITIALIZED,
249     BACKUP_USER_DATA,
250     ROLLBACK_USER_DATA,
251     UNKNOWN_ERROR,
252   };
253
254   enum BackendMode {
255     IDLE,       // No backend.
256     SYNC,       // Backend for syncing.
257     BACKUP,     // Backend for backup.
258     ROLLBACK    // Backend for rollback.
259   };
260
261   // Default sync server URL.
262   static const char* kSyncServerUrl;
263   // Sync server URL for dev channel users
264   static const char* kDevServerUrl;
265
266   // Takes ownership of |factory| and |signin_wrapper|.
267   ProfileSyncService(
268       ProfileSyncComponentsFactory* factory,
269       Profile* profile,
270       scoped_ptr<ManagedUserSigninManagerWrapper> signin_wrapper,
271       ProfileOAuth2TokenService* oauth2_token_service,
272       browser_sync::ProfileSyncServiceStartBehavior start_behavior);
273   virtual ~ProfileSyncService();
274
275   // Initializes the object. This must be called at most once, and
276   // immediately after an object of this class is constructed.
277   void Initialize();
278
279   virtual void SetSyncSetupCompleted();
280
281   // ProfileSyncServiceBase implementation.
282   virtual bool HasSyncSetupCompleted() const OVERRIDE;
283   virtual bool ShouldPushChanges() OVERRIDE;
284   virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE;
285   virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE;
286   virtual void RemoveObserver(
287       ProfileSyncServiceBase::Observer* observer) OVERRIDE;
288   virtual bool HasObserver(
289       ProfileSyncServiceBase::Observer* observer) const OVERRIDE;
290
291
292   void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
293   void RemoveProtocolEventObserver(
294       browser_sync::ProtocolEventObserver* observer);
295
296   void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
297   void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
298
299   // Asynchronously fetches base::Value representations of all sync nodes and
300   // returns them to the specified callback on this thread.
301   //
302   // These requests can live a long time and return when you least expect it.
303   // For safety, the callback should be bound to some sort of WeakPtr<> or
304   // scoped_refptr<>.
305   void GetAllNodes(
306       const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
307
308   void RegisterAuthNotifications();
309   void UnregisterAuthNotifications();
310
311   // Returns true if sync is enabled/not suppressed and the user is logged in.
312   // (being logged in does not mean that tokens are available - tokens may
313   // be missing because they have not loaded yet, or because they were deleted
314   // due to http://crbug.com/121755).
315   // Virtual to enable mocking in tests.
316   // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
317   // callers use a seemingly arbitrary / redundant / bug prone combination of
318   // this method, IsSyncAccessible, and others.
319   virtual bool IsSyncEnabledAndLoggedIn();
320
321   // Return whether OAuth2 refresh token is loaded and available for the backend
322   // to start up. Virtual to enable mocking in tests.
323   virtual bool IsOAuthRefreshTokenAvailable();
324
325   // Registers a data type controller with the sync service.  This
326   // makes the data type controller available for use, it does not
327   // enable or activate the synchronization of the data type (see
328   // ActivateDataType).  Takes ownership of the pointer.
329   void RegisterDataTypeController(
330       browser_sync::DataTypeController* data_type_controller);
331
332   // Registers a type whose sync storage will not be managed by the
333   // ProfileSyncService.  It declares that this sync type may be activated at
334   // some point in the future.  This function call does not enable or activate
335   // the syncing of this type
336   void RegisterNonBlockingType(syncer::ModelType type);
337
338   // Called by a component that supports non-blocking sync when it is ready to
339   // initialize its connection to the sync backend.
340   //
341   // If policy allows for syncing this type (ie. it is "preferred"), then this
342   // should result in a message to enable syncing for this type when the sync
343   // backend is available.  If the type is not to be synced, this should result
344   // in a message that allows the component to delete its local sync state.
345   void InitializeNonBlockingType(
346       syncer::ModelType type,
347       scoped_refptr<base::SequencedTaskRunner> task_runner,
348       base::WeakPtr<syncer::NonBlockingTypeProcessor> processor);
349
350   // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
351   // currently syncing, returns NULL.
352   virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
353
354   // Returns the SyncableService for syncer::SESSIONS.
355   virtual syncer::SyncableService* GetSessionsSyncableService();
356
357   // SyncInternalApiDelegate implementation.
358   //
359   // Returns sync's representation of the local device info.
360   // Return value is an empty scoped_ptr if the device info is unavailable.
361   virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo()
362       const OVERRIDE;
363
364   // Gets the guid for the local device. Can be used by other layers to
365   // to distinguish sync data that belongs to the local device vs data
366   // that belongs to remote devices. Returns empty string if sync is not
367   // initialized. The GUID is not persistent across Chrome signout/signin.
368   // If you sign out of Chrome and sign in, a new GUID is generated.
369   virtual std::string GetLocalSyncCacheGUID() const OVERRIDE;
370
371   // Returns sync's representation of the device info for a client identified
372   // by |client_id|. Return value is an empty scoped ptr if the device info
373   // is unavailable.
374   virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo(
375       const std::string& client_id) const;
376
377   // Gets the device info for all devices signed into the account associated
378   // with this profile.
379   virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const;
380
381   // Notifies the observer of any device info changes.
382   virtual void AddObserverForDeviceInfoChange(
383       browser_sync::SyncedDeviceTracker::Observer* observer);
384
385   // Removes the observer from device info notification.
386   virtual void RemoveObserverForDeviceInfoChange(
387       browser_sync::SyncedDeviceTracker::Observer* observer);
388
389   // Fills state_map with a map of current data types that are possible to
390   // sync, as well as their states.
391   void GetDataTypeControllerStates(
392     browser_sync::DataTypeController::StateMap* state_map) const;
393
394   // Disables sync for user. Use ShowLoginDialog to enable.
395   virtual void DisableForUser();
396
397   // Disables sync for the user and prevents it from starting on next restart.
398   virtual void StopSyncingPermanently();
399
400   // SyncFrontend implementation.
401   virtual void OnBackendInitialized(
402       const syncer::WeakHandle<syncer::JsBackend>& js_backend,
403       const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
404           debug_info_listener,
405       bool success) OVERRIDE;
406   virtual void OnSyncCycleCompleted() OVERRIDE;
407   virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
408   virtual void OnDirectoryTypeCommitCounterUpdated(
409       syncer::ModelType type,
410       const syncer::CommitCounters& counters) OVERRIDE;
411   virtual void OnDirectoryTypeUpdateCounterUpdated(
412       syncer::ModelType type,
413       const syncer::UpdateCounters& counters) OVERRIDE;
414   virtual void OnDirectoryTypeStatusCounterUpdated(
415       syncer::ModelType type,
416       const syncer::StatusCounters& counters) OVERRIDE;
417   virtual void OnSyncConfigureRetry() OVERRIDE;
418   virtual void OnConnectionStatusChange(
419       syncer::ConnectionStatus status) OVERRIDE;
420   virtual void OnPassphraseRequired(
421       syncer::PassphraseRequiredReason reason,
422       const sync_pb::EncryptedData& pending_keys) OVERRIDE;
423   virtual void OnPassphraseAccepted() OVERRIDE;
424   virtual void OnEncryptedTypesChanged(
425       syncer::ModelTypeSet encrypted_types,
426       bool encrypt_everything) OVERRIDE;
427   virtual void OnEncryptionComplete() OVERRIDE;
428   virtual void OnMigrationNeededForTypes(
429       syncer::ModelTypeSet types) OVERRIDE;
430   virtual void OnExperimentsChanged(
431       const syncer::Experiments& experiments) OVERRIDE;
432   virtual void OnActionableError(
433       const syncer::SyncProtocolError& error) OVERRIDE;
434
435   // DataTypeManagerObserver implementation.
436   virtual void OnConfigureDone(
437       const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE;
438   virtual void OnConfigureRetry() OVERRIDE;
439   virtual void OnConfigureStart() OVERRIDE;
440
441   // DataTypeEncryptionHandler implementation.
442   virtual bool IsPassphraseRequired() const OVERRIDE;
443   virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE;
444
445   // SigninManagerBase::Observer implementation.
446   virtual void GoogleSigninSucceeded(const std::string& username,
447                                      const std::string& password) OVERRIDE;
448   virtual void GoogleSignedOut(const std::string& username) OVERRIDE;
449
450   // Called when a user chooses which data types to sync as part of the sync
451   // setup wizard.  |sync_everything| represents whether they chose the
452   // "keep everything synced" option; if true, |chosen_types| will be ignored
453   // and all data types will be synced.  |sync_everything| means "sync all
454   // current and future data types."
455   virtual void OnUserChoseDatatypes(bool sync_everything,
456       syncer::ModelTypeSet chosen_types);
457
458   // Get the sync status code.
459   SyncStatusSummary QuerySyncStatusSummary();
460
461   // Get a description of the sync status for displaying in the user interface.
462   std::string QuerySyncStatusSummaryString();
463
464   // Initializes a struct of status indicators with data from the backend.
465   // Returns false if the backend was not available for querying; in that case
466   // the struct will be filled with default data.
467   virtual bool QueryDetailedSyncStatus(
468       browser_sync::SyncBackendHost::Status* result);
469
470   virtual const GoogleServiceAuthError& GetAuthError() const;
471
472   // Returns true if initial sync setup is in progress (does not return true
473   // if the user is customizing sync after already completing setup once).
474   // ProfileSyncService uses this to determine if it's OK to start syncing, or
475   // if the user is still setting up the initial sync configuration.
476   virtual bool FirstSetupInProgress() const;
477
478   // Called by the UI to notify the ProfileSyncService that UI is visible so it
479   // will not start syncing. This tells sync whether it's safe to start
480   // downloading data types yet (we don't start syncing until after sync setup
481   // is complete). The UI calls this as soon as any part of the signin wizard is
482   // displayed (even just the login UI).
483   // If |setup_in_progress| is false, this also kicks the sync engine to ensure
484   // that data download starts.
485   virtual void SetSetupInProgress(bool setup_in_progress);
486
487   // Returns true if the SyncBackendHost has told us it's ready to accept
488   // changes.
489   // [REMARK] - it is safe to call this function only from the ui thread.
490   // because the variable is not thread safe and should only be accessed from
491   // single thread. If we want multiple threads to access this(and there is
492   // currently no need to do so) we need to protect this with a lock.
493   // TODO(timsteele): What happens if the bookmark model is loaded, a change
494   // takes place, and the backend isn't initialized yet?
495   virtual bool sync_initialized() const;
496
497   virtual bool HasUnrecoverableError() const;
498   const std::string& unrecoverable_error_message() {
499     return unrecoverable_error_message_;
500   }
501   tracked_objects::Location unrecoverable_error_location() {
502     return unrecoverable_error_location_;
503   }
504
505   // Returns true if OnPassphraseRequired has been called for decryption and
506   // we have an encrypted data type enabled.
507   virtual bool IsPassphraseRequiredForDecryption() const;
508
509   syncer::PassphraseRequiredReason passphrase_required_reason() const {
510     return passphrase_required_reason_;
511   }
512
513   // Returns a user-friendly string form of last synced time (in minutes).
514   virtual base::string16 GetLastSyncedTimeString() const;
515
516   // Returns a human readable string describing backend initialization state.
517   std::string GetBackendInitializationStateString() const;
518
519   // Returns true if startup is suppressed (i.e. user has stopped syncing via
520   // the google dashboard).
521   virtual bool IsStartSuppressed() const;
522
523   ProfileSyncComponentsFactory* factory() { return factory_.get(); }
524
525   // The profile we are syncing for.
526   Profile* profile() const { return profile_; }
527
528   // Returns a weak pointer to the service's JsController.
529   // Overrideable for testing purposes.
530   virtual base::WeakPtr<syncer::JsController> GetJsController();
531
532   // Record stats on various events.
533   static void SyncEvent(SyncEventCodes code);
534
535   // Returns whether sync is enabled.  Sync can be enabled/disabled both
536   // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
537   // command-line switches).
538   // Profile::IsSyncAccessible() is probably a better signal than this function.
539   // This function can be called from any thread, and the implementation doesn't
540   // assume it's running on the UI thread.
541   static bool IsSyncEnabled();
542
543   // Returns whether sync is managed, i.e. controlled by configuration
544   // management. If so, the user is not allowed to configure sync.
545   virtual bool IsManaged() const;
546
547   // syncer::UnrecoverableErrorHandler implementation.
548   virtual void OnUnrecoverableError(
549       const tracked_objects::Location& from_here,
550       const std::string& message) OVERRIDE;
551
552   // Called when a datatype wishes to disable itself. Note, this does not change
553   // preferred state of a datatype and is not persisted across restarts.
554   virtual void DisableDatatype(syncer::ModelType type,
555                                const tracked_objects::Location& from_here,
556                                std::string message);
557
558   // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
559   // not change the preferred state of a datatype, and is not persisted across
560   // restarts.
561   void ReenableDatatype(syncer::ModelType type);
562
563   // The functions below (until ActivateDataType()) should only be
564   // called if sync_initialized() is true.
565
566   // TODO(akalin): This is called mostly by ModelAssociators and
567   // tests.  Figure out how to pass the handle to the ModelAssociators
568   // directly, figure out how to expose this to tests, and remove this
569   // function.
570   virtual syncer::UserShare* GetUserShare() const;
571
572   // TODO(akalin): These two functions are used only by
573   // ProfileSyncServiceHarness.  Figure out a different way to expose
574   // this info to that class, and remove these functions.
575
576   virtual syncer::sessions::SyncSessionSnapshot
577       GetLastSessionSnapshot() const;
578
579   // Returns whether or not the underlying sync engine has made any
580   // local changes to items that have not yet been synced with the
581   // server.
582   bool HasUnsyncedItems() const;
583
584   // Used by ProfileSyncServiceHarness.  May return NULL.
585   browser_sync::BackendMigrator* GetBackendMigratorForTest();
586
587   // Used by tests to inspect interaction with OAuth2TokenService.
588   bool IsRetryingAccessTokenFetchForTest() const;
589
590   // Used by tests to inspect the OAuth2 access tokens used by PSS.
591   std::string GetAccessTokenForTest() const;
592
593   // TODO(sync): This is only used in tests.  Can we remove it?
594   void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
595
596   // Returns a ListValue indicating the status of all registered types.
597   //
598   // The format is:
599   // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
600   // where <name> is a type's name, <value> is a string providing details for
601   // the type's status, and <status> is one of "error", "warning" or "ok"
602   // depending on the type's current status.
603   //
604   // This function is used by about_sync_util.cc to help populate the about:sync
605   // page.  It returns a ListValue rather than a DictionaryValue in part to make
606   // it easier to iterate over its elements when constructing that page.
607   base::Value* GetTypeStatusMap() const;
608
609   // Overridden by tests.
610   // TODO(zea): Remove these and have the dtc's call directly into the SBH.
611   virtual void DeactivateDataType(syncer::ModelType type);
612
613   // SyncPrefObserver implementation.
614   virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE;
615
616   // Changes which data types we're going to be syncing to |preferred_types|.
617   // If it is running, the DataTypeManager will be instructed to reconfigure
618   // the sync backend so that exactly these datatypes are actively synced.  See
619   // class comment for more on what it means for a datatype to be Preferred.
620   virtual void ChangePreferredDataTypes(
621       syncer::ModelTypeSet preferred_types);
622
623   // Returns the set of types which are preferred for enabling. This is a
624   // superset of the active types (see GetActiveDataTypes()).
625   virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
626
627   // Returns the set of directory types which are preferred for enabling.
628   virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
629
630   // Returns the set of off-thread types which are preferred for enabling.
631   virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
632
633   // Gets the set of all data types that could be allowed (the set that
634   // should be advertised to the user).  These will typically only change
635   // via a command-line option.  See class comment for more on what it means
636   // for a datatype to be Registered.
637   virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
638
639   // Gets the set of directory types which could be allowed.
640   virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
641
642   // Gets the set of off-thread types which could be allowed.
643   virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
644
645   // Checks whether the Cryptographer is ready to encrypt and decrypt updates
646   // for sensitive data types. Caller must be holding a
647   // syncapi::BaseTransaction to ensure thread safety.
648   virtual bool IsCryptographerReady(
649       const syncer::BaseTransaction* trans) const;
650
651   // Returns true if a secondary (explicit) passphrase is being used. It is not
652   // legal to call this method before the backend is initialized.
653   virtual bool IsUsingSecondaryPassphrase() const;
654
655   // Returns the actual passphrase type being used for encryption.
656   virtual syncer::PassphraseType GetPassphraseType() const;
657
658   // Returns the time the current explicit passphrase (if any), was set.
659   // If no secondary passphrase is in use, or no time is available, returns an
660   // unset base::Time.
661   virtual base::Time GetExplicitPassphraseTime() const;
662
663   // Note about setting passphrases: There are different scenarios under which
664   // we might want to apply a passphrase. It could be for first-time encryption,
665   // re-encryption, or for decryption by clients that sign in at a later time.
666   // In addition, encryption can either be done using a custom passphrase, or by
667   // reusing the GAIA password. Depending on what is happening in the system,
668   // callers should determine which of the two methods below must be used.
669
670   // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
671   // specifies whether the passphrase is a custom passphrase or the GAIA
672   // password being reused as a passphrase.
673   // TODO(atwilson): Change this so external callers can only set an EXPLICIT
674   // passphrase with this API.
675   virtual void SetEncryptionPassphrase(const std::string& passphrase,
676                                        PassphraseType type);
677
678   // Asynchronously decrypts pending keys using |passphrase|. Returns false
679   // immediately if the passphrase could not be used to decrypt a locally cached
680   // copy of encrypted keys; returns true otherwise.
681   virtual bool SetDecryptionPassphrase(const std::string& passphrase)
682       WARN_UNUSED_RESULT;
683
684   // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
685   // after calling this to force the encryption to occur.
686   virtual void EnableEncryptEverything();
687
688   // Returns true if we are currently set to encrypt all the sync data. Note:
689   // this is based on the cryptographer's settings, so if the user has recently
690   // requested encryption to be turned on, this may not be true yet. For that,
691   // encryption_pending() must be checked.
692   virtual bool EncryptEverythingEnabled() const;
693
694   // Returns true if the syncer is waiting for new datatypes to be encrypted.
695   virtual bool encryption_pending() const;
696
697   const GURL& sync_service_url() const { return sync_service_url_; }
698   SigninManagerBase* signin() const;
699
700   // Used by tests.
701   bool auto_start_enabled() const;
702   bool setup_in_progress() const;
703
704   // Stops the sync backend and sets the flag for suppressing sync startup.
705   void StopAndSuppress();
706
707   // Resets the flag for suppressing sync startup and starts the sync backend.
708   virtual void UnsuppressAndStart();
709
710   // Marks all currently registered types as "acknowledged" so we won't prompt
711   // the user about them any more.
712   void AcknowledgeSyncedTypes();
713
714   SyncErrorController* sync_error_controller() {
715     return sync_error_controller_.get();
716   }
717
718   // TODO(sync): This is only used in tests.  Can we remove it?
719   const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const;
720
721   browser_sync::DataTypeManager::ConfigureStatus configure_status() {
722     return configure_status_;
723   }
724
725   // If true, the ProfileSyncService has detected that a new GAIA signin has
726   // succeeded, and is waiting for initialization to complete. This is used by
727   // the UI to differentiate between a new auth error (encountered as part of
728   // the initialization process) and a pre-existing auth error that just hasn't
729   // been cleared yet. Virtual for testing purposes.
730   virtual bool waiting_for_auth() const;
731
732   // The set of currently enabled sync experiments.
733   const syncer::Experiments& current_experiments() const;
734
735   // OAuth2TokenService::Consumer implementation.
736   virtual void OnGetTokenSuccess(
737       const OAuth2TokenService::Request* request,
738       const std::string& access_token,
739       const base::Time& expiration_time) OVERRIDE;
740   virtual void OnGetTokenFailure(
741       const OAuth2TokenService::Request* request,
742       const GoogleServiceAuthError& error) OVERRIDE;
743
744   // OAuth2TokenService::Observer implementation.
745   virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE;
746   virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE;
747   virtual void OnRefreshTokensLoaded() OVERRIDE;
748
749   // KeyedService implementation.  This must be called exactly
750   // once (before this object is destroyed).
751   virtual void Shutdown() OVERRIDE;
752
753   // Called when a datatype (SyncableService) has a need for sync to start
754   // ASAP, presumably because a local change event has occurred but we're
755   // still in deferred start mode, meaning the SyncableService hasn't been
756   // told to MergeDataAndStartSyncing yet.
757   void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
758
759   // Return sync token status.
760   SyncTokenStatus GetSyncTokenStatus() const;
761
762   browser_sync::FaviconCache* GetFaviconCache();
763
764   // Overrides the NetworkResources used for Sync connections.
765   // This function takes ownership of |network_resources|.
766   void OverrideNetworkResourcesForTest(
767       scoped_ptr<syncer::NetworkResources> network_resources);
768
769   virtual bool IsSessionsDataTypeControllerRunning() const;
770
771   void SetBackupStartDelayForTest(base::TimeDelta delay);
772
773   BackendMode backend_mode() const {
774     return backend_mode_;
775   }
776
777   void SetClearingBrowseringDataForTesting(
778       base::Callback<void(Profile*, base::Time, base::Time)> c);
779
780   // Return the base URL of the Sync Server.
781   static GURL GetSyncServiceURL(const base::CommandLine& command_line);
782
783  protected:
784   // Helper to configure the priority data types.
785   void ConfigurePriorityDataTypes();
786
787   // Helper to install and configure a data type manager.
788   void ConfigureDataTypeManager();
789
790   // Shuts down the backend sync components.
791   // |option| indicates if syncing is being disabled or not, and whether
792   // to claim ownership of sync thread from backend.
793   void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option);
794
795   // Return SyncCredentials from the OAuth2TokenService.
796   syncer::SyncCredentials GetCredentials();
797
798   virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
799
800   const browser_sync::DataTypeController::TypeMap&
801       directory_data_type_controllers() {
802     return directory_data_type_controllers_;
803   }
804
805   // Helper method for managing encryption UI.
806   bool IsEncryptedDatatypeEnabled() const;
807
808   // Helper for OnUnrecoverableError.
809   // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
810   // and in SyncBackendHost::Shutdown.
811   void OnUnrecoverableErrorImpl(
812       const tracked_objects::Location& from_here,
813       const std::string& message,
814       bool delete_sync_database);
815
816   // This is a cache of the last authentication response we received from the
817   // sync server. The UI queries this to display appropriate messaging to the
818   // user.
819   GoogleServiceAuthError last_auth_error_;
820
821   // Our asynchronous backend to communicate with sync components living on
822   // other threads.
823   scoped_ptr<browser_sync::SyncBackendHost> backend_;
824
825   // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
826   // was required for encryption, decryption with a cached passphrase, or
827   // because a new passphrase is required?
828   syncer::PassphraseRequiredReason passphrase_required_reason_;
829
830  private:
831   enum UnrecoverableErrorReason {
832     ERROR_REASON_UNSET,
833     ERROR_REASON_SYNCER,
834     ERROR_REASON_BACKEND_INIT_FAILURE,
835     ERROR_REASON_CONFIGURATION_RETRY,
836     ERROR_REASON_CONFIGURATION_FAILURE,
837     ERROR_REASON_ACTIONABLE_ERROR,
838     ERROR_REASON_LIMIT
839   };
840
841   enum AuthErrorMetric {
842     AUTH_ERROR_ENCOUNTERED,
843     AUTH_ERROR_FIXED,
844     AUTH_ERROR_LIMIT
845   };
846
847   friend class ProfileSyncServicePasswordTest;
848   friend class SyncTest;
849   friend class TestProfileSyncService;
850   FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
851
852   // Update the last auth error and notify observers of error state.
853   void UpdateAuthErrorState(const GoogleServiceAuthError& error);
854
855   // Detects and attempts to recover from a previous improper datatype
856   // configuration where Keep Everything Synced and the preferred types were
857   // not correctly set.
858   void TrySyncDatatypePrefRecovery();
859
860   // Puts the backend's sync scheduler into NORMAL mode.
861   // Called when configuration is complete.
862   void StartSyncingWithServer();
863
864   // Called when we've determined that we don't need a passphrase (either
865   // because OnPassphraseAccepted() was called, or because we've gotten a
866   // OnPassphraseRequired() but no data types are enabled).
867   void ResolvePassphraseRequired();
868
869   // During initial signin, ProfileSyncService caches the user's signin
870   // passphrase so it can be used to encrypt/decrypt data after sync starts up.
871   // This routine is invoked once the backend has started up to use the
872   // cached passphrase and clear it out when it is done.
873   void ConsumeCachedPassphraseIfPossible();
874
875   // RequestAccessToken initiates RPC to request downscoped access token from
876   // refresh token. This happens when a new OAuth2 login token is loaded and
877   // when sync server returns AUTH_ERROR which indicates it is time to refresh
878   // token.
879   virtual void RequestAccessToken();
880
881   // Return true if backend should start from a fresh sync DB.
882   bool ShouldDeleteSyncFolder();
883
884   // If |delete_sync_data_folder| is true, then this method will delete all
885   // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
886   void InitializeBackend(bool delete_sync_data_folder);
887
888   // Initializes the various settings from the command line.
889   void InitSettings();
890
891   // Sets the last synced time to the current time.
892   void UpdateLastSyncedTime();
893
894   void NotifyObservers();
895   void NotifySyncCycleCompleted();
896
897   void ClearStaleErrors();
898
899   void ClearUnrecoverableError();
900
901   // Starts up the backend sync components. |mode| specifies the kind of
902   // backend to start, one of SYNC, BACKUP or ROLLBACK.
903   virtual void StartUpSlowBackendComponents(BackendMode mode);
904
905   // About-flags experiment names for datatypes that aren't enabled by default
906   // yet.
907   static std::string GetExperimentNameForDataType(
908       syncer::ModelType data_type);
909
910   // Create and register a new datatype controller.
911   void RegisterNewDataType(syncer::ModelType data_type);
912
913   // Reconfigures the data type manager with the latest enabled types.
914   // Note: Does not initialize the backend if it is not already initialized.
915   // This function needs to be called only after sync has been initialized
916   // (i.e.,only for reconfigurations). The reason we don't initialize the
917   // backend is because if we had encountered an unrecoverable error we don't
918   // want to startup once more.
919   virtual void ReconfigureDatatypeManager();
920
921   // Called when the user changes the sync configuration, to update the UMA
922   // stats.
923   void UpdateSelectedTypesHistogram(
924       bool sync_everything,
925       const syncer::ModelTypeSet chosen_types) const;
926
927 #if defined(OS_CHROMEOS)
928   // Refresh spare sync bootstrap token for re-enabling the sync service.
929   // Called on successful sign-in notifications.
930   void RefreshSpareBootstrapToken(const std::string& passphrase);
931 #endif
932
933   // Internal unrecoverable error handler. Used to track error reason via
934   // Sync.UnrecoverableErrors histogram.
935   void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
936                                     const std::string& message,
937                                     bool delete_sync_database,
938                                     UnrecoverableErrorReason reason);
939
940   // Returns the type of manager to use according to |backend_mode_|.
941   syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
942
943   // Update UMA for syncing backend.
944   void UpdateBackendInitUMA(bool success);
945
946   // Various setup following backend initialization, mostly for syncing backend.
947   void PostBackendInitialization();
948
949   // True if a syncing backend exists.
950   bool HasSyncingBackend() const;
951
952   // Update first sync time stored in preferences
953   void UpdateFirstSyncTimePref();
954
955   // Clear browsing data since first sync during rollback.
956   void ClearBrowsingDataSinceFirstSync();
957
958  // Factory used to create various dependent objects.
959   scoped_ptr<ProfileSyncComponentsFactory> factory_;
960
961   // The profile whose data we are synchronizing.
962   Profile* profile_;
963
964   // The class that handles getting, setting, and persisting sync
965   // preferences.
966   sync_driver::SyncPrefs sync_prefs_;
967
968   // TODO(ncarter): Put this in a profile, once there is UI for it.
969   // This specifies where to find the sync server.
970   const GURL sync_service_url_;
971
972   // The last time we detected a successful transition from SYNCING state.
973   // Our backend notifies us whenever we should take a new snapshot.
974   base::Time last_synced_time_;
975
976   // The time that OnConfigureStart is called. This member is zero if
977   // OnConfigureStart has not yet been called, and is reset to zero once
978   // OnConfigureDone is called.
979   base::Time sync_configure_start_time_;
980
981   // Indicates if this is the first time sync is being configured.  This value
982   // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
983   bool is_first_time_sync_configure_;
984
985   // List of available data type controllers for directory types.
986   browser_sync::DataTypeController::TypeMap directory_data_type_controllers_;
987
988   // Whether the SyncBackendHost has been initialized.
989   bool backend_initialized_;
990
991   // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
992   // ProfileSyncService from starting backend till browser restarted or user
993   // signed out.
994   bool sync_disabled_by_admin_;
995
996   // Set to true if a signin has completed but we're still waiting for the
997   // backend to refresh its credentials.
998   bool is_auth_in_progress_;
999
1000   // Encapsulates user signin - used to set/get the user's authenticated
1001   // email address.
1002   const scoped_ptr<ManagedUserSigninManagerWrapper> signin_;
1003
1004   // Information describing an unrecoverable error.
1005   UnrecoverableErrorReason unrecoverable_error_reason_;
1006   std::string unrecoverable_error_message_;
1007   tracked_objects::Location unrecoverable_error_location_;
1008
1009   // Manages the start and stop of the directory data types.
1010   scoped_ptr<browser_sync::DataTypeManager> directory_data_type_manager_;
1011
1012   // Manager for the non-blocking data types.
1013   browser_sync::NonBlockingDataTypeManager non_blocking_data_type_manager_;
1014
1015   ObserverList<ProfileSyncServiceBase::Observer> observers_;
1016   ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
1017   ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
1018
1019   syncer::SyncJsController sync_js_controller_;
1020
1021   // This allows us to gracefully handle an ABORTED return code from the
1022   // DataTypeManager in the event that the server informed us to cease and
1023   // desist syncing immediately.
1024   bool expect_sync_configuration_aborted_;
1025
1026   // Sometimes we need to temporarily hold on to a passphrase because we don't
1027   // yet have a backend to send it to.  This happens during initialization as
1028   // we don't StartUp until we have a valid token, which happens after valid
1029   // credentials were provided.
1030   std::string cached_passphrase_;
1031
1032   // The current set of encrypted types.  Always a superset of
1033   // syncer::Cryptographer::SensitiveTypes().
1034   syncer::ModelTypeSet encrypted_types_;
1035
1036   // Whether we want to encrypt everything.
1037   bool encrypt_everything_;
1038
1039   // Whether we're waiting for an attempt to encryption all sync data to
1040   // complete. We track this at this layer in order to allow the user to cancel
1041   // if they e.g. don't remember their explicit passphrase.
1042   bool encryption_pending_;
1043
1044   scoped_ptr<browser_sync::BackendMigrator> migrator_;
1045
1046   // This is the last |SyncProtocolError| we received from the server that had
1047   // an action set on it.
1048   syncer::SyncProtocolError last_actionable_error_;
1049
1050   // Exposes sync errors to the UI.
1051   scoped_ptr<SyncErrorController> sync_error_controller_;
1052
1053   // Tracks the set of failed data types (those that encounter an error
1054   // or must delay loading for some reason).
1055   browser_sync::FailedDataTypesHandler failed_data_types_handler_;
1056
1057   browser_sync::DataTypeManager::ConfigureStatus configure_status_;
1058
1059   // The set of currently enabled sync experiments.
1060   syncer::Experiments current_experiments_;
1061
1062   // Sync's internal debug info listener. Used to record datatype configuration
1063   // and association information.
1064   syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1065
1066   // A thread where all the sync operations happen.
1067   // OWNERSHIP Notes:
1068   //     * Created when backend starts for the first time.
1069   //     * If sync is disabled, PSS claims ownership from backend.
1070   //     * If sync is reenabled, PSS passes ownership to new backend.
1071   scoped_ptr<base::Thread> sync_thread_;
1072
1073   // ProfileSyncService uses this service to get access tokens.
1074   ProfileOAuth2TokenService* const oauth2_token_service_;
1075
1076   // ProfileSyncService needs to remember access token in order to invalidate it
1077   // with OAuth2TokenService.
1078   std::string access_token_;
1079
1080   // ProfileSyncService needs to hold reference to access_token_request_ for
1081   // the duration of request in order to receive callbacks.
1082   scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1083
1084   // If RequestAccessToken fails with transient error then retry requesting
1085   // access token with exponential backoff.
1086   base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1087   net::BackoffEntry request_access_token_backoff_;
1088
1089   base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1090
1091   // We don't use |weak_factory_| for the StartupController because the weak
1092   // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1093   // [Initialize -> sync disabled/shutdown] lifetime.  We don't pass
1094   // StartupController an Unretained reference to future-proof against
1095   // the controller impl changing to post tasks. Therefore, we have a separate
1096   // factory.
1097   base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1098
1099   // States related to sync token and connection.
1100   base::Time connection_status_update_time_;
1101   syncer::ConnectionStatus connection_status_;
1102   base::Time token_request_time_;
1103   base::Time token_receive_time_;
1104   GoogleServiceAuthError last_get_token_error_;
1105   base::Time next_token_request_time_;
1106
1107   // Locally owned SyncableService implementations.
1108   scoped_ptr<SessionsSyncManager> sessions_sync_manager_;
1109
1110   scoped_ptr<syncer::NetworkResources> network_resources_;
1111
1112   browser_sync::StartupController startup_controller_;
1113
1114   browser_sync::BackupRollbackController backup_rollback_controller_;
1115
1116   // Mode of current backend.
1117   BackendMode backend_mode_;
1118
1119   // When browser starts, delay sync backup/rollback backend start for this
1120   // time.
1121   base::TimeDelta backup_start_delay_;
1122
1123   base::Callback<void(Profile*, base::Time, base::Time)> clear_browsing_data_;
1124
1125   DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1126 };
1127
1128 bool ShouldShowActionOnUI(
1129     const syncer::SyncProtocolError& error);
1130
1131
1132 #endif  // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_