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