Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blobf40ac51e93bda65448bb5706489188ba75b71882
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/files/file_path.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/strings/string16.h"
22 #include "base/time/time.h"
23 #include "base/timer/timer.h"
24 #include "chrome/browser/browsing_data/browsing_data_remover.h"
25 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h"
26 #include "chrome/browser/sync/backup_rollback_controller.h"
27 #include "chrome/browser/sync/glue/sync_backend_host.h"
28 #include "chrome/browser/sync/profile_sync_service_base.h"
29 #include "chrome/browser/sync/profile_sync_service_observer.h"
30 #include "chrome/browser/sync/protocol_event_observer.h"
31 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
32 #include "chrome/browser/sync/startup_controller.h"
33 #include "chrome/browser/sync/sync_stopped_reporter.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/data_type_status_table.h"
41 #include "components/sync_driver/device_info_sync_service.h"
42 #include "components/sync_driver/local_device_info_provider.h"
43 #include "components/sync_driver/non_blocking_data_type_manager.h"
44 #include "components/sync_driver/sync_frontend.h"
45 #include "components/sync_driver/sync_prefs.h"
46 #include "google_apis/gaia/google_service_auth_error.h"
47 #include "google_apis/gaia/oauth2_token_service.h"
48 #include "net/base/backoff_entry.h"
49 #include "sync/internal_api/public/base/model_type.h"
50 #include "sync/internal_api/public/engine/model_safe_worker.h"
51 #include "sync/internal_api/public/shutdown_reason.h"
52 #include "sync/internal_api/public/sync_manager_factory.h"
53 #include "sync/internal_api/public/util/experiments.h"
54 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
55 #include "sync/js/sync_js_controller.h"
56 #include "url/gurl.h"
58 class Profile;
59 class ProfileOAuth2TokenService;
60 class ProfileSyncComponentsFactory;
61 class SupervisedUserSigninManagerWrapper;
62 class SyncErrorController;
63 class SyncTypePreferenceProvider;
65 namespace base {
66 class CommandLine;
69 namespace browser_sync {
70 class BackendMigrator;
71 class FaviconCache;
72 class JsController;
73 class OpenTabsUIDelegate;
75 namespace sessions {
76 class SyncSessionSnapshot;
77 } // namespace sessions
78 } // namespace browser_sync
80 namespace sync_driver {
81 class ChangeProcessor;
82 class DataTypeManager;
83 class DeviceInfoSyncService;
84 class LocalDeviceInfoProvider;
85 } // namespace sync_driver
87 namespace syncer {
88 class BaseTransaction;
89 class NetworkResources;
90 struct CommitCounters;
91 struct StatusCounters;
92 struct SyncCredentials;
93 struct UpdateCounters;
94 struct UserShare;
95 } // namespace syncer
97 namespace sync_pb {
98 class EncryptedData;
99 } // namespace sync_pb
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 ~ProfileSyncService() override;
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 bool HasSyncSetupCompleted() const override;
290 bool SyncActive() const override;
291 syncer::ModelTypeSet GetActiveDataTypes() const override;
292 void AddObserver(ProfileSyncServiceBase::Observer* observer) override;
293 void RemoveObserver(ProfileSyncServiceBase::Observer* observer) override;
294 bool HasObserver(
295 const ProfileSyncServiceBase::Observer* observer) const override;
297 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
298 void RemoveProtocolEventObserver(
299 browser_sync::ProtocolEventObserver* observer);
301 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
302 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
304 // Add a sync type preference provider. Each provider may only be added once.
305 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
306 // Remove a sync type preference provider. May only be called for providers
307 // that have been added. Providers must not remove themselves while being
308 // called back.
309 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
310 // Check whether a given sync type preference provider has been added.
311 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
313 // Asynchronously fetches base::Value representations of all sync nodes and
314 // returns them to the specified callback on this thread.
316 // These requests can live a long time and return when you least expect it.
317 // For safety, the callback should be bound to some sort of WeakPtr<> or
318 // scoped_refptr<>.
319 void GetAllNodes(
320 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
322 void RegisterAuthNotifications();
323 void UnregisterAuthNotifications();
325 // Returns true if sync is enabled/not suppressed and the user is logged in.
326 // (being logged in does not mean that tokens are available - tokens may
327 // be missing because they have not loaded yet, or because they were deleted
328 // due to http://crbug.com/121755).
329 // Virtual to enable mocking in tests.
330 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside
331 // callers use a seemingly arbitrary / redundant / bug prone combination of
332 // this method, IsSyncAccessible, and others.
333 virtual bool IsSyncEnabledAndLoggedIn();
335 // Return whether OAuth2 refresh token is loaded and available for the backend
336 // to start up. Virtual to enable mocking in tests.
337 virtual bool IsOAuthRefreshTokenAvailable();
339 // Registers a data type controller with the sync service. This
340 // makes the data type controller available for use, it does not
341 // enable or activate the synchronization of the data type (see
342 // ActivateDataType). Takes ownership of the pointer.
343 void RegisterDataTypeController(
344 sync_driver::DataTypeController* data_type_controller);
346 // Registers a type whose sync storage will not be managed by the
347 // ProfileSyncService. It declares that this sync type may be activated at
348 // some point in the future. This function call does not enable or activate
349 // the syncing of this type
350 void RegisterNonBlockingType(syncer::ModelType type);
352 // Called by a component that supports non-blocking sync when it is ready to
353 // initialize its connection to the sync backend.
355 // If policy allows for syncing this type (ie. it is "preferred"), then this
356 // should result in a message to enable syncing for this type when the sync
357 // backend is available. If the type is not to be synced, this should result
358 // in a message that allows the component to delete its local sync state.
359 void InitializeNonBlockingType(
360 syncer::ModelType type,
361 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
362 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& proxy);
364 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not
365 // currently syncing, returns NULL.
366 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate();
368 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
369 virtual browser_sync::SyncedWindowDelegatesGetter*
370 GetSyncedWindowDelegatesGetter() const;
372 // Returns the SyncableService for syncer::SESSIONS.
373 virtual syncer::SyncableService* GetSessionsSyncableService();
375 // Returns the SyncableService for syncer::DEVICE_INFO.
376 virtual syncer::SyncableService* GetDeviceInfoSyncableService();
378 // Returns DeviceInfo provider for the local device.
379 virtual sync_driver::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider();
381 // Returns synced devices tracker.
382 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
384 // Fills state_map with a map of current data types that are possible to
385 // sync, as well as their states.
386 void GetDataTypeControllerStates(
387 sync_driver::DataTypeController::StateMap* state_map) const;
389 // Disables sync for user. Use ShowLoginDialog to enable.
390 virtual void DisableForUser();
392 // Disables sync for the user and prevents it from starting on next restart.
393 virtual void StopSyncingPermanently();
395 // SyncFrontend implementation.
396 void OnBackendInitialized(
397 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
398 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
399 debug_info_listener,
400 const std::string& cache_guid,
401 bool success) override;
402 void OnSyncCycleCompleted() override;
403 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
404 void OnDirectoryTypeCommitCounterUpdated(
405 syncer::ModelType type,
406 const syncer::CommitCounters& counters) override;
407 void OnDirectoryTypeUpdateCounterUpdated(
408 syncer::ModelType type,
409 const syncer::UpdateCounters& counters) override;
410 void OnDirectoryTypeStatusCounterUpdated(
411 syncer::ModelType type,
412 const syncer::StatusCounters& counters) override;
413 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
414 void OnPassphraseRequired(
415 syncer::PassphraseRequiredReason reason,
416 const sync_pb::EncryptedData& pending_keys) override;
417 void OnPassphraseAccepted() override;
418 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
419 bool encrypt_everything) override;
420 void OnEncryptionComplete() override;
421 void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override;
422 void OnExperimentsChanged(const syncer::Experiments& experiments) override;
423 void OnActionableError(const syncer::SyncProtocolError& error) override;
425 // DataTypeManagerObserver implementation.
426 void OnConfigureDone(
427 const sync_driver::DataTypeManager::ConfigureResult& result) override;
428 void OnConfigureStart() override;
430 // DataTypeEncryptionHandler implementation.
431 bool IsPassphraseRequired() const override;
432 syncer::ModelTypeSet GetEncryptedDataTypes() const override;
434 // SigninManagerBase::Observer implementation.
435 void GoogleSigninSucceeded(const std::string& account_id,
436 const std::string& username,
437 const std::string& password) override;
438 void GoogleSignedOut(const std::string& account_id,
439 const std::string& username) override;
441 // Called when a user chooses which data types to sync as part of the sync
442 // setup wizard. |sync_everything| represents whether they chose the
443 // "keep everything synced" option; if true, |chosen_types| will be ignored
444 // and all data types will be synced. |sync_everything| means "sync all
445 // current and future data types."
446 virtual void OnUserChoseDatatypes(bool sync_everything,
447 syncer::ModelTypeSet chosen_types);
449 // Get the sync status code.
450 SyncStatusSummary QuerySyncStatusSummary();
452 // Get a description of the sync status for displaying in the user interface.
453 std::string QuerySyncStatusSummaryString();
455 // Initializes a struct of status indicators with data from the backend.
456 // Returns false if the backend was not available for querying; in that case
457 // the struct will be filled with default data.
458 virtual bool QueryDetailedSyncStatus(
459 browser_sync::SyncBackendHost::Status* result);
461 virtual const GoogleServiceAuthError& GetAuthError() const;
463 // Returns true if initial sync setup is in progress (does not return true
464 // if the user is customizing sync after already completing setup once).
465 // ProfileSyncService uses this to determine if it's OK to start syncing, or
466 // if the user is still setting up the initial sync configuration.
467 virtual bool FirstSetupInProgress() const;
469 // Called by the UI to notify the ProfileSyncService that UI is visible so it
470 // will not start syncing. This tells sync whether it's safe to start
471 // downloading data types yet (we don't start syncing until after sync setup
472 // is complete). The UI calls this as soon as any part of the signin wizard is
473 // displayed (even just the login UI).
474 // If |setup_in_progress| is false, this also kicks the sync engine to ensure
475 // that data download starts. In this case, |ReconfigureDatatypeManager| will
476 // get triggered.
477 virtual void SetSetupInProgress(bool setup_in_progress);
479 // Reconfigures the data type manager with the latest enabled types.
480 // Note: Does not initialize the backend if it is not already initialized.
481 // This function needs to be called only after sync has been initialized
482 // (i.e.,only for reconfigurations). The reason we don't initialize the
483 // backend is because if we had encountered an unrecoverable error we don't
484 // want to startup once more.
485 // This function is called by |SetSetupInProgress|.
486 virtual void ReconfigureDatatypeManager();
488 virtual bool HasUnrecoverableError() const;
489 const std::string& unrecoverable_error_message() {
490 return unrecoverable_error_message_;
492 tracked_objects::Location unrecoverable_error_location() {
493 return unrecoverable_error_location_;
496 // Returns true if OnPassphraseRequired has been called for decryption and
497 // we have an encrypted data type enabled.
498 virtual bool IsPassphraseRequiredForDecryption() const;
500 syncer::PassphraseRequiredReason passphrase_required_reason() const {
501 return passphrase_required_reason_;
504 // Returns a user-friendly string form of last synced time (in minutes).
505 virtual base::string16 GetLastSyncedTimeString() const;
507 // Returns a human readable string describing backend initialization state.
508 std::string GetBackendInitializationStateString() const;
510 // Returns true if startup is suppressed (i.e. user has stopped syncing via
511 // the google dashboard).
512 virtual bool IsStartSuppressed() const;
514 ProfileSyncComponentsFactory* factory() { return factory_.get(); }
516 // The profile we are syncing for.
517 Profile* profile() const { return profile_; }
519 // Returns a weak pointer to the service's JsController.
520 // Overrideable for testing purposes.
521 virtual base::WeakPtr<syncer::JsController> GetJsController();
523 // Record stats on various events.
524 static void SyncEvent(SyncEventCodes code);
526 // Returns whether sync is enabled. Sync can be enabled/disabled both
527 // at compile time (e.g., on a per-OS basis) or at run time (e.g.,
528 // command-line switches).
529 // Profile::IsSyncAccessible() is probably a better signal than this function.
530 // This function can be called from any thread, and the implementation doesn't
531 // assume it's running on the UI thread.
532 static bool IsSyncEnabled();
534 // Returns whether sync is managed, i.e. controlled by configuration
535 // management. If so, the user is not allowed to configure sync.
536 virtual bool IsManaged() const;
538 // syncer::UnrecoverableErrorHandler implementation.
539 void OnUnrecoverableError(const tracked_objects::Location& from_here,
540 const std::string& message) override;
542 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does
543 // not change the preferred state of a datatype, and is not persisted across
544 // restarts.
545 void ReenableDatatype(syncer::ModelType type);
547 // The functions below (until ActivateDataType()) should only be
548 // called if backend_initialized() is true.
550 // TODO(akalin): This is called mostly by ModelAssociators and
551 // tests. Figure out how to pass the handle to the ModelAssociators
552 // directly, figure out how to expose this to tests, and remove this
553 // function.
554 virtual syncer::UserShare* GetUserShare() const;
556 // TODO(akalin): These two functions are used only by
557 // ProfileSyncServiceHarness. Figure out a different way to expose
558 // this info to that class, and remove these functions.
560 virtual syncer::sessions::SyncSessionSnapshot
561 GetLastSessionSnapshot() const;
563 // Returns whether or not the underlying sync engine has made any
564 // local changes to items that have not yet been synced with the
565 // server.
566 bool HasUnsyncedItems() const;
568 // Used by ProfileSyncServiceHarness. May return NULL.
569 browser_sync::BackendMigrator* GetBackendMigratorForTest();
571 // Used by tests to inspect interaction with OAuth2TokenService.
572 bool IsRetryingAccessTokenFetchForTest() const;
574 // Used by tests to inspect the OAuth2 access tokens used by PSS.
575 std::string GetAccessTokenForTest() const;
577 // TODO(sync): This is only used in tests. Can we remove it?
578 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
580 // Returns a ListValue indicating the status of all registered types.
582 // The format is:
583 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ]
584 // where <name> is a type's name, <value> is a string providing details for
585 // the type's status, and <status> is one of "error", "warning" or "ok"
586 // depending on the type's current status.
588 // This function is used by about_sync_util.cc to help populate the about:sync
589 // page. It returns a ListValue rather than a DictionaryValue in part to make
590 // it easier to iterate over its elements when constructing that page.
591 base::Value* GetTypeStatusMap() const;
593 // Overridden by tests.
594 // TODO(zea): Remove these and have the dtc's call directly into the SBH.
595 virtual void DeactivateDataType(syncer::ModelType type);
597 // SyncPrefObserver implementation.
598 void OnSyncManagedPrefChange(bool is_sync_managed) override;
600 // Changes which data types we're going to be syncing to |preferred_types|.
601 // If it is running, the DataTypeManager will be instructed to reconfigure
602 // the sync backend so that exactly these datatypes are actively synced. See
603 // class comment for more on what it means for a datatype to be Preferred.
604 virtual void ChangePreferredDataTypes(
605 syncer::ModelTypeSet preferred_types);
607 // Returns the set of types which are preferred for enabling. This is a
608 // superset of the active types (see GetActiveDataTypes()).
609 virtual syncer::ModelTypeSet GetPreferredDataTypes() const;
611 // Returns the set of directory types which are preferred for enabling.
612 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
614 // Returns the set of off-thread types which are preferred for enabling.
615 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
617 // Returns the set of types which are enforced programmatically and can not
618 // be disabled by the user.
619 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
621 // Gets the set of all data types that could be allowed (the set that
622 // should be advertised to the user). These will typically only change
623 // via a command-line option. See class comment for more on what it means
624 // for a datatype to be Registered.
625 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
627 // Gets the set of directory types which could be allowed.
628 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
630 // Gets the set of off-thread types which could be allowed.
631 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
633 // Checks whether the Cryptographer is ready to encrypt and decrypt updates
634 // for sensitive data types. Caller must be holding a
635 // syncapi::BaseTransaction to ensure thread safety.
636 virtual bool IsCryptographerReady(
637 const syncer::BaseTransaction* trans) const;
639 // Returns true if a secondary (explicit) passphrase is being used. It is not
640 // legal to call this method before the backend is initialized.
641 virtual bool IsUsingSecondaryPassphrase() const;
643 // Returns the actual passphrase type being used for encryption.
644 virtual syncer::PassphraseType GetPassphraseType() const;
646 // Returns the time the current explicit passphrase (if any), was set.
647 // If no secondary passphrase is in use, or no time is available, returns an
648 // unset base::Time.
649 virtual base::Time GetExplicitPassphraseTime() const;
651 // Note about setting passphrases: There are different scenarios under which
652 // we might want to apply a passphrase. It could be for first-time encryption,
653 // re-encryption, or for decryption by clients that sign in at a later time.
654 // In addition, encryption can either be done using a custom passphrase, or by
655 // reusing the GAIA password. Depending on what is happening in the system,
656 // callers should determine which of the two methods below must be used.
658 // Asynchronously sets the passphrase to |passphrase| for encryption. |type|
659 // specifies whether the passphrase is a custom passphrase or the GAIA
660 // password being reused as a passphrase.
661 // TODO(atwilson): Change this so external callers can only set an EXPLICIT
662 // passphrase with this API.
663 virtual void SetEncryptionPassphrase(const std::string& passphrase,
664 PassphraseType type);
666 // Asynchronously decrypts pending keys using |passphrase|. Returns false
667 // immediately if the passphrase could not be used to decrypt a locally cached
668 // copy of encrypted keys; returns true otherwise.
669 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
670 WARN_UNUSED_RESULT;
672 // Returns true if encrypting all the sync data is allowed. If this method
673 // returns false, EnableEncryptEverything() should not be called.
674 virtual bool EncryptEverythingAllowed() const;
676 // Sets whether encrypting all the sync data is allowed or not.
677 virtual void SetEncryptEverythingAllowed(bool allowed);
679 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes()
680 // after calling this to force the encryption to occur.
681 virtual void EnableEncryptEverything();
683 // Returns true if we are currently set to encrypt all the sync data. Note:
684 // this is based on the cryptographer's settings, so if the user has recently
685 // requested encryption to be turned on, this may not be true yet. For that,
686 // encryption_pending() must be checked.
687 virtual bool EncryptEverythingEnabled() const;
689 // Returns true if the syncer is waiting for new datatypes to be encrypted.
690 virtual bool encryption_pending() const;
692 const GURL& sync_service_url() const { return sync_service_url_; }
693 SigninManagerBase* signin() const;
695 // Used by tests.
696 bool auto_start_enabled() const;
697 bool setup_in_progress() const;
699 // Stops the sync backend and sets the flag for suppressing sync startup.
700 void StopAndSuppress();
702 // Resets the flag for suppressing sync startup and starts the sync backend.
703 virtual void UnsuppressAndStart();
705 // Marks all currently registered types as "acknowledged" so we won't prompt
706 // the user about them any more.
707 void AcknowledgeSyncedTypes();
709 SyncErrorController* sync_error_controller() {
710 return sync_error_controller_.get();
713 // TODO(sync): This is only used in tests. Can we remove it?
714 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
716 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
717 return configure_status_;
720 // If true, the ProfileSyncService has detected that a new GAIA signin has
721 // succeeded, and is waiting for initialization to complete. This is used by
722 // the UI to differentiate between a new auth error (encountered as part of
723 // the initialization process) and a pre-existing auth error that just hasn't
724 // been cleared yet. Virtual for testing purposes.
725 virtual bool waiting_for_auth() const;
727 // The set of currently enabled sync experiments.
728 const syncer::Experiments& current_experiments() const;
730 // OAuth2TokenService::Consumer implementation.
731 void OnGetTokenSuccess(const OAuth2TokenService::Request* request,
732 const std::string& access_token,
733 const base::Time& expiration_time) override;
734 void OnGetTokenFailure(const OAuth2TokenService::Request* request,
735 const GoogleServiceAuthError& error) override;
737 // OAuth2TokenService::Observer implementation.
738 void OnRefreshTokenAvailable(const std::string& account_id) override;
739 void OnRefreshTokenRevoked(const std::string& account_id) override;
740 void OnRefreshTokensLoaded() override;
742 // KeyedService implementation. This must be called exactly
743 // once (before this object is destroyed).
744 void Shutdown() override;
746 // Called when a datatype (SyncableService) has a need for sync to start
747 // ASAP, presumably because a local change event has occurred but we're
748 // still in deferred start mode, meaning the SyncableService hasn't been
749 // told to MergeDataAndStartSyncing yet.
750 void OnDataTypeRequestsSyncStartup(syncer::ModelType type);
752 // Return sync token status.
753 SyncTokenStatus GetSyncTokenStatus() const;
755 browser_sync::FaviconCache* GetFaviconCache();
757 // Overrides the NetworkResources used for Sync connections.
758 // This function takes ownership of |network_resources|.
759 void OverrideNetworkResourcesForTest(
760 scoped_ptr<syncer::NetworkResources> network_resources);
762 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
764 // Returns true if the SyncBackendHost has told us it's ready to accept
765 // changes. This should only be used for sync's internal configuration logic
766 // (such as deciding when to prompt for an encryption passphrase).
767 virtual bool backend_initialized() const;
769 // Returns the current mode the backend is in.
770 BackendMode backend_mode() const;
772 // Whether the data types active for the current mode have finished
773 // configuration.
774 bool ConfigurationDone() const;
776 // Helpers for testing rollback.
777 void SetBrowsingDataRemoverObserverForTesting(
778 BrowsingDataRemover::Observer* observer);
779 void SetClearingBrowseringDataForTesting(base::Callback<
780 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
783 // Return the base URL of the Sync Server.
784 static GURL GetSyncServiceURL(const base::CommandLine& command_line);
786 base::Time GetDeviceBackupTimeForTesting() const;
788 // This triggers a Directory::SaveChanges() call on the sync thread.
789 // It should be used to persist data to disk when the process might be
790 // killed in the near future.
791 void FlushDirectory() const;
793 // Needed to test whether the directory is deleted properly.
794 base::FilePath GetDirectoryPathForTest() const;
796 // Sometimes we need to wait for tasks on the sync thread in tests.
797 base::MessageLoop* GetSyncLoopForTest() const;
799 protected:
800 // Helper to configure the priority data types.
801 void ConfigurePriorityDataTypes();
803 // Helper to install and configure a data type manager.
804 void ConfigureDataTypeManager();
806 // Shuts down the backend sync components.
807 // |reason| dictates if syncing is being disabled or not, and whether
808 // to claim ownership of sync thread from backend.
809 void ShutdownImpl(syncer::ShutdownReason reason);
811 // Return SyncCredentials from the OAuth2TokenService.
812 syncer::SyncCredentials GetCredentials();
814 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
816 const sync_driver::DataTypeController::TypeMap&
817 directory_data_type_controllers() {
818 return directory_data_type_controllers_;
821 // Helper method for managing encryption UI.
822 bool IsEncryptedDatatypeEnabled() const;
824 // Helper for OnUnrecoverableError.
825 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
826 // and in SyncBackendHost::Shutdown.
827 void OnUnrecoverableErrorImpl(
828 const tracked_objects::Location& from_here,
829 const std::string& message,
830 bool delete_sync_database);
832 virtual bool NeedBackup() const;
834 // This is a cache of the last authentication response we received from the
835 // sync server. The UI queries this to display appropriate messaging to the
836 // user.
837 GoogleServiceAuthError last_auth_error_;
839 // Our asynchronous backend to communicate with sync components living on
840 // other threads.
841 scoped_ptr<browser_sync::SyncBackendHost> backend_;
843 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
844 // was required for encryption, decryption with a cached passphrase, or
845 // because a new passphrase is required?
846 syncer::PassphraseRequiredReason passphrase_required_reason_;
848 private:
849 enum UnrecoverableErrorReason {
850 ERROR_REASON_UNSET,
851 ERROR_REASON_SYNCER,
852 ERROR_REASON_BACKEND_INIT_FAILURE,
853 ERROR_REASON_CONFIGURATION_RETRY,
854 ERROR_REASON_CONFIGURATION_FAILURE,
855 ERROR_REASON_ACTIONABLE_ERROR,
856 ERROR_REASON_LIMIT
859 enum AuthErrorMetric {
860 AUTH_ERROR_ENCOUNTERED,
861 AUTH_ERROR_FIXED,
862 AUTH_ERROR_LIMIT
865 friend class ProfileSyncServicePasswordTest;
866 friend class SyncTest;
867 friend class TestProfileSyncService;
868 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
870 // Update the last auth error and notify observers of error state.
871 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
873 // Detects and attempts to recover from a previous improper datatype
874 // configuration where Keep Everything Synced and the preferred types were
875 // not correctly set.
876 void TrySyncDatatypePrefRecovery();
878 // Puts the backend's sync scheduler into NORMAL mode.
879 // Called when configuration is complete.
880 void StartSyncingWithServer();
882 // Called when we've determined that we don't need a passphrase (either
883 // because OnPassphraseAccepted() was called, or because we've gotten a
884 // OnPassphraseRequired() but no data types are enabled).
885 void ResolvePassphraseRequired();
887 // During initial signin, ProfileSyncService caches the user's signin
888 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
889 // This routine is invoked once the backend has started up to use the
890 // cached passphrase and clear it out when it is done.
891 void ConsumeCachedPassphraseIfPossible();
893 // RequestAccessToken initiates RPC to request downscoped access token from
894 // refresh token. This happens when a new OAuth2 login token is loaded and
895 // when sync server returns AUTH_ERROR which indicates it is time to refresh
896 // token.
897 virtual void RequestAccessToken();
899 // Return true if backend should start from a fresh sync DB.
900 bool ShouldDeleteSyncFolder();
902 // If |delete_sync_data_folder| is true, then this method will delete all
903 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
904 void InitializeBackend(bool delete_sync_data_folder);
906 // Initializes the various settings from the command line.
907 void InitSettings();
909 // Sets the last synced time to the current time.
910 void UpdateLastSyncedTime();
912 void NotifyObservers();
913 void NotifySyncCycleCompleted();
915 void ClearStaleErrors();
917 void ClearUnrecoverableError();
919 // Starts up the backend sync components. |mode| specifies the kind of
920 // backend to start, one of SYNC, BACKUP or ROLLBACK.
921 virtual void StartUpSlowBackendComponents(BackendMode mode);
923 // About-flags experiment names for datatypes that aren't enabled by default
924 // yet.
925 static std::string GetExperimentNameForDataType(
926 syncer::ModelType data_type);
928 // Create and register a new datatype controller.
929 void RegisterNewDataType(syncer::ModelType data_type);
931 // Collects preferred sync data types from |preference_providers_|.
932 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
934 // Called when the user changes the sync configuration, to update the UMA
935 // stats.
936 void UpdateSelectedTypesHistogram(
937 bool sync_everything,
938 const syncer::ModelTypeSet chosen_types) const;
940 #if defined(OS_CHROMEOS)
941 // Refresh spare sync bootstrap token for re-enabling the sync service.
942 // Called on successful sign-in notifications.
943 void RefreshSpareBootstrapToken(const std::string& passphrase);
944 #endif
946 // Internal unrecoverable error handler. Used to track error reason via
947 // Sync.UnrecoverableErrors histogram.
948 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
949 const std::string& message,
950 bool delete_sync_database,
951 UnrecoverableErrorReason reason);
953 // Returns the type of manager to use according to |backend_mode_|.
954 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
956 // Update UMA for syncing backend.
957 void UpdateBackendInitUMA(bool success);
959 // Various setup following backend initialization, mostly for syncing backend.
960 void PostBackendInitialization();
962 // True if a syncing backend exists.
963 bool HasSyncingBackend() const;
965 // Update first sync time stored in preferences
966 void UpdateFirstSyncTimePref();
968 // Clear browsing data since first sync during rollback.
969 void ClearBrowsingDataSinceFirstSync();
971 // Post background task to check sync backup DB state if needed.
972 void CheckSyncBackupIfNeeded();
974 // Callback to receive backup DB check result.
975 void CheckSyncBackupCallback(base::Time backup_time);
977 // Callback function to call |startup_controller_|.TryStart() after
978 // backup/rollback finishes;
979 void TryStartSyncAfterBackup();
981 // Clean up prefs and backup DB when rollback is not needed.
982 void CleanUpBackup();
984 // Tell the sync server that this client has disabled sync.
985 void RemoveClientFromServer() const;
987 // Factory used to create various dependent objects.
988 scoped_ptr<ProfileSyncComponentsFactory> factory_;
990 // The profile whose data we are synchronizing.
991 Profile* profile_;
993 // The class that handles getting, setting, and persisting sync
994 // preferences.
995 sync_driver::SyncPrefs sync_prefs_;
997 // TODO(ncarter): Put this in a profile, once there is UI for it.
998 // This specifies where to find the sync server.
999 const GURL sync_service_url_;
1001 // The time that OnConfigureStart is called. This member is zero if
1002 // OnConfigureStart has not yet been called, and is reset to zero once
1003 // OnConfigureDone is called.
1004 base::Time sync_configure_start_time_;
1006 // Indicates if this is the first time sync is being configured. This value
1007 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
1008 bool is_first_time_sync_configure_;
1010 // List of available data type controllers for directory types.
1011 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
1013 // Whether the SyncBackendHost has been initialized.
1014 bool backend_initialized_;
1016 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
1017 // ProfileSyncService from starting backend till browser restarted or user
1018 // signed out.
1019 bool sync_disabled_by_admin_;
1021 // Set to true if a signin has completed but we're still waiting for the
1022 // backend to refresh its credentials.
1023 bool is_auth_in_progress_;
1025 // Encapsulates user signin - used to set/get the user's authenticated
1026 // email address.
1027 const scoped_ptr<SupervisedUserSigninManagerWrapper> signin_;
1029 // Information describing an unrecoverable error.
1030 UnrecoverableErrorReason unrecoverable_error_reason_;
1031 std::string unrecoverable_error_message_;
1032 tracked_objects::Location unrecoverable_error_location_;
1034 // Manages the start and stop of the directory data types.
1035 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
1037 // Manager for the non-blocking data types.
1038 sync_driver::NonBlockingDataTypeManager non_blocking_data_type_manager_;
1040 ObserverList<ProfileSyncServiceBase::Observer> observers_;
1041 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_;
1042 ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
1044 std::set<SyncTypePreferenceProvider*> preference_providers_;
1046 syncer::SyncJsController sync_js_controller_;
1048 // This allows us to gracefully handle an ABORTED return code from the
1049 // DataTypeManager in the event that the server informed us to cease and
1050 // desist syncing immediately.
1051 bool expect_sync_configuration_aborted_;
1053 // Sometimes we need to temporarily hold on to a passphrase because we don't
1054 // yet have a backend to send it to. This happens during initialization as
1055 // we don't StartUp until we have a valid token, which happens after valid
1056 // credentials were provided.
1057 std::string cached_passphrase_;
1059 // The current set of encrypted types. Always a superset of
1060 // syncer::Cryptographer::SensitiveTypes().
1061 syncer::ModelTypeSet encrypted_types_;
1063 // Whether encrypting everything is allowed.
1064 bool encrypt_everything_allowed_;
1066 // Whether we want to encrypt everything.
1067 bool encrypt_everything_;
1069 // Whether we're waiting for an attempt to encryption all sync data to
1070 // complete. We track this at this layer in order to allow the user to cancel
1071 // if they e.g. don't remember their explicit passphrase.
1072 bool encryption_pending_;
1074 scoped_ptr<browser_sync::BackendMigrator> migrator_;
1076 // This is the last |SyncProtocolError| we received from the server that had
1077 // an action set on it.
1078 syncer::SyncProtocolError last_actionable_error_;
1080 // Exposes sync errors to the UI.
1081 scoped_ptr<SyncErrorController> sync_error_controller_;
1083 // Tracks the set of failed data types (those that encounter an error
1084 // or must delay loading for some reason).
1085 sync_driver::DataTypeStatusTable data_type_status_table_;
1087 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
1089 // The set of currently enabled sync experiments.
1090 syncer::Experiments current_experiments_;
1092 // Sync's internal debug info listener. Used to record datatype configuration
1093 // and association information.
1094 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
1096 // A thread where all the sync operations happen.
1097 // OWNERSHIP Notes:
1098 // * Created when backend starts for the first time.
1099 // * If sync is disabled, PSS claims ownership from backend.
1100 // * If sync is reenabled, PSS passes ownership to new backend.
1101 scoped_ptr<base::Thread> sync_thread_;
1103 // ProfileSyncService uses this service to get access tokens.
1104 ProfileOAuth2TokenService* const oauth2_token_service_;
1106 // ProfileSyncService needs to remember access token in order to invalidate it
1107 // with OAuth2TokenService.
1108 std::string access_token_;
1110 // ProfileSyncService needs to hold reference to access_token_request_ for
1111 // the duration of request in order to receive callbacks.
1112 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
1114 // If RequestAccessToken fails with transient error then retry requesting
1115 // access token with exponential backoff.
1116 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
1117 net::BackoffEntry request_access_token_backoff_;
1119 // States related to sync token and connection.
1120 base::Time connection_status_update_time_;
1121 syncer::ConnectionStatus connection_status_;
1122 base::Time token_request_time_;
1123 base::Time token_receive_time_;
1124 GoogleServiceAuthError last_get_token_error_;
1125 base::Time next_token_request_time_;
1127 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
1129 // Locally owned SyncableService implementations.
1130 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
1131 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
1133 scoped_ptr<syncer::NetworkResources> network_resources_;
1135 scoped_ptr<browser_sync::StartupController> startup_controller_;
1137 scoped_ptr<browser_sync::BackupRollbackController>
1138 backup_rollback_controller_;
1140 // Mode of current backend.
1141 BackendMode backend_mode_;
1143 // Whether backup is needed before sync starts.
1144 bool need_backup_;
1146 // Whether backup is finished.
1147 bool backup_finished_;
1149 base::Time backup_start_time_;
1151 base::Callback<
1152 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1153 clear_browsing_data_;
1155 // Last time when pre-sync data was saved. NULL pointer means backup data
1156 // state is unknown. If time value is null, backup data doesn't exist.
1157 scoped_ptr<base::Time> last_backup_time_;
1159 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1161 // The full path to the sync data directory.
1162 base::FilePath directory_path_;
1164 scoped_ptr<browser_sync::SyncStoppedReporter> sync_stopped_reporter_;
1166 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1168 // We don't use |weak_factory_| for the StartupController because the weak
1169 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1170 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1171 // StartupController an Unretained reference to future-proof against
1172 // the controller impl changing to post tasks. Therefore, we have a separate
1173 // factory.
1174 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1176 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1179 bool ShouldShowActionOnUI(
1180 const syncer::SyncProtocolError& error);
1183 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_