Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.h
blob1391f16c382d7e530c12f95b93ce68e172d75ee7
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/memory_pressure_listener.h"
18 #include "base/memory/scoped_ptr.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/backup_rollback_controller.h"
26 #include "chrome/browser/sync/glue/sync_backend_host.h"
27 #include "chrome/browser/sync/sessions/sessions_sync_manager.h"
28 #include "chrome/browser/sync/startup_controller.h"
29 #include "components/keyed_service/core/keyed_service.h"
30 #include "components/signin/core/browser/signin_manager_base.h"
31 #include "components/sync_driver/data_type_controller.h"
32 #include "components/sync_driver/data_type_manager.h"
33 #include "components/sync_driver/data_type_manager_observer.h"
34 #include "components/sync_driver/data_type_status_table.h"
35 #include "components/sync_driver/device_info_sync_service.h"
36 #include "components/sync_driver/local_device_info_provider.h"
37 #include "components/sync_driver/non_blocking_data_type_manager.h"
38 #include "components/sync_driver/protocol_event_observer.h"
39 #include "components/sync_driver/sync_frontend.h"
40 #include "components/sync_driver/sync_prefs.h"
41 #include "components/sync_driver/sync_service.h"
42 #include "components/sync_driver/sync_stopped_reporter.h"
43 #include "google_apis/gaia/google_service_auth_error.h"
44 #include "google_apis/gaia/oauth2_token_service.h"
45 #include "net/base/backoff_entry.h"
46 #include "sync/internal_api/public/base/model_type.h"
47 #include "sync/internal_api/public/engine/model_safe_worker.h"
48 #include "sync/internal_api/public/shutdown_reason.h"
49 #include "sync/internal_api/public/sync_manager_factory.h"
50 #include "sync/internal_api/public/user_share.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 SigninManagerWrapper;
59 class SyncErrorController;
60 class SyncTypePreferenceProvider;
62 namespace base {
63 class CommandLine;
66 namespace browser_sync {
67 class BackendMigrator;
68 class FaviconCache;
69 class JsController;
71 namespace sessions {
72 class SyncSessionSnapshot;
73 } // namespace sessions
74 } // namespace browser_sync
76 namespace sync_driver {
77 class ChangeProcessor;
78 class DataTypeManager;
79 class DeviceInfoSyncService;
80 class LocalDeviceInfoProvider;
81 class OpenTabsUIDelegate;
82 class SyncApiComponentFactory;
83 } // namespace sync_driver
85 namespace syncer {
86 class BaseTransaction;
87 class NetworkResources;
88 struct CommitCounters;
89 struct StatusCounters;
90 struct SyncCredentials;
91 struct UpdateCounters;
92 struct UserShare;
93 } // namespace syncer
95 namespace sync_pb {
96 class EncryptedData;
97 } // namespace sync_pb
99 // ProfileSyncService is the layer between browser subsystems like bookmarks,
100 // and the sync backend. Each subsystem is logically thought of as being
101 // a sync datatype.
103 // Individual datatypes can, at any point, be in a variety of stages of being
104 // "enabled". Here are some specific terms for concepts used in this class:
106 // 'Registered' (feature suppression for a datatype)
108 // When a datatype is registered, the user has the option of syncing it.
109 // The sync opt-in UI will show only registered types; a checkbox should
110 // never be shown for an unregistered type, and nor should it ever be
111 // synced.
113 // A datatype is considered registered once RegisterDataTypeController
114 // has been called with that datatype's DataTypeController.
116 // 'Preferred' (user preferences and opt-out for a datatype)
118 // This means the user's opt-in or opt-out preference on a per-datatype
119 // basis. The sync service will try to make active exactly these types.
120 // If a user has opted out of syncing a particular datatype, it will
121 // be registered, but not preferred.
123 // This state is controlled by the ConfigurePreferredDataTypes and
124 // GetPreferredDataTypes. They are stored in the preferences system,
125 // and persist; though if a datatype is not registered, it cannot
126 // be a preferred datatype.
128 // 'Active' (run-time initialization of sync system for a datatype)
130 // An active datatype is a preferred datatype that is actively being
131 // synchronized: the syncer has been instructed to querying the server
132 // for this datatype, first-time merges have finished, and there is an
133 // actively installed ChangeProcessor that listens for changes to this
134 // datatype, propagating such changes into and out of the sync backend
135 // as necessary.
137 // When a datatype is in the process of becoming active, it may be
138 // in some intermediate state. Those finer-grained intermediate states
139 // are differentiated by the DataTypeController state.
141 // Sync Configuration:
143 // Sync configuration is accomplished via the following APIs:
144 // * OnUserChoseDatatypes(): Set the data types the user wants to sync.
145 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data
146 // using the passed passphrase.
147 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed
148 // passphrase.
150 // Additionally, the current sync configuration can be fetched by calling
151 // * GetRegisteredDataTypes()
152 // * GetPreferredDataTypes()
153 // * GetActiveDataTypes()
154 // * IsUsingSecondaryPassphrase()
155 // * EncryptEverythingEnabled()
156 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption()
158 // The "sync everything" state cannot be read from ProfileSyncService, but
159 // is instead pulled from SyncPrefs.HasKeepEverythingSynced().
161 // Initial sync setup:
163 // For privacy reasons, it is usually desirable to avoid syncing any data
164 // types until the user has finished setting up sync. There are two APIs
165 // that control the initial sync download:
167 // * SetSyncSetupCompleted()
168 // * SetSetupInProgress()
170 // SetSyncSetupCompleted() should be called once the user has finished setting
171 // up sync at least once on their account. SetSetupInProgress(true) should be
172 // called while the user is actively configuring their account, and then
173 // SetSetupInProgress(false) should be called when configuration is complete.
174 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has
175 // been called, then the sync engine knows not to download any user data.
177 // When initial sync is complete, the UI code should call
178 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will
179 // tell the sync engine that setup is completed and it can begin downloading
180 // data from the sync server.
182 class ProfileSyncService : public sync_driver::SyncService,
183 public sync_driver::SyncFrontend,
184 public sync_driver::SyncPrefObserver,
185 public sync_driver::DataTypeManagerObserver,
186 public syncer::UnrecoverableErrorHandler,
187 public KeyedService,
188 public OAuth2TokenService::Consumer,
189 public OAuth2TokenService::Observer,
190 public SigninManagerBase::Observer {
191 public:
192 typedef browser_sync::SyncBackendHost::Status Status;
194 enum SyncEventCodes {
195 MIN_SYNC_EVENT_CODE = 0,
197 // Events starting the sync service.
198 START_FROM_NTP = 1, // Sync was started from the ad in NTP
199 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu.
200 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options.
201 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager.
202 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu.
203 START_FROM_URL = 6, // Sync was started from a typed URL.
205 // Events regarding cancellation of the signon process of sync.
206 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting
207 // username and password.
208 CANCEL_DURING_SIGNON = 11, // Cancelled after auth.
209 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data
210 // types and clicking OK.
211 // Events resulting in the stoppage of sync service.
212 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options.
213 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings.
215 // Miscellaneous events caused by sync service.
217 MAX_SYNC_EVENT_CODE
220 enum SyncStatusSummary {
221 UNRECOVERABLE_ERROR,
222 NOT_ENABLED,
223 SETUP_INCOMPLETE,
224 DATATYPES_NOT_INITIALIZED,
225 INITIALIZED,
226 BACKUP_USER_DATA,
227 ROLLBACK_USER_DATA,
228 UNKNOWN_ERROR,
231 enum BackendMode {
232 IDLE, // No backend.
233 SYNC, // Backend for syncing.
234 BACKUP, // Backend for backup.
235 ROLLBACK // Backend for rollback.
238 // Takes ownership of |factory| and |signin_wrapper|.
239 ProfileSyncService(
240 scoped_ptr<sync_driver::SyncApiComponentFactory> factory,
241 Profile* profile,
242 scoped_ptr<SigninManagerWrapper> signin_wrapper,
243 ProfileOAuth2TokenService* oauth2_token_service,
244 browser_sync::ProfileSyncServiceStartBehavior start_behavior);
245 ~ProfileSyncService() override;
247 // Initializes the object. This must be called at most once, and
248 // immediately after an object of this class is constructed.
249 void Initialize();
251 // sync_driver::SyncService implementation
252 bool HasSyncSetupCompleted() const override;
253 bool IsSyncAllowed() const override;
254 bool IsSyncActive() const override;
255 void OnDataTypeRequestsSyncStartup(syncer::ModelType type) override;
256 bool CanSyncStart() const override;
257 void RequestStop(SyncStopDataFate data_fate) override;
258 void RequestStart() override;
259 syncer::ModelTypeSet GetActiveDataTypes() const override;
260 syncer::ModelTypeSet GetPreferredDataTypes() const override;
261 void OnUserChoseDatatypes(bool sync_everything,
262 syncer::ModelTypeSet chosen_types) override;
263 void SetSyncSetupCompleted() override;
264 bool FirstSetupInProgress() const override;
265 void SetSetupInProgress(bool setup_in_progress) override;
266 bool setup_in_progress() const override;
267 bool ConfigurationDone() const override;
268 const GoogleServiceAuthError& GetAuthError() const override;
269 bool HasUnrecoverableError() const override;
270 bool backend_initialized() const override;
271 sync_driver::OpenTabsUIDelegate* GetOpenTabsUIDelegate() override;
272 bool IsPassphraseRequiredForDecryption() const override;
273 base::Time GetExplicitPassphraseTime() const override;
274 bool IsUsingSecondaryPassphrase() const override;
275 void EnableEncryptEverything() override;
276 bool EncryptEverythingEnabled() const override;
277 void SetEncryptionPassphrase(const std::string& passphrase,
278 PassphraseType type) override;
279 bool SetDecryptionPassphrase(const std::string& passphrase) override
280 WARN_UNUSED_RESULT;
281 bool IsCryptographerReady(
282 const syncer::BaseTransaction* trans) const override;
283 syncer::UserShare* GetUserShare() const override;
284 sync_driver::LocalDeviceInfoProvider* GetLocalDeviceInfoProvider()
285 const override;
286 void AddObserver(sync_driver::SyncServiceObserver* observer) override;
287 void RemoveObserver(sync_driver::SyncServiceObserver* observer) override;
288 bool HasObserver(
289 const sync_driver::SyncServiceObserver* observer) const override;
290 void RegisterDataTypeController(
291 sync_driver::DataTypeController* data_type_controller) override;
292 void ReenableDatatype(syncer::ModelType type) override;
293 void DeactivateDataType(syncer::ModelType type) override;
294 SyncTokenStatus GetSyncTokenStatus() const override;
295 std::string QuerySyncStatusSummaryString() override;
296 bool QueryDetailedSyncStatus(syncer::SyncStatus* result) override;
297 base::string16 GetLastSyncedTimeString() const override;
298 std::string GetBackendInitializationStateString() const override;
299 syncer::sessions::SyncSessionSnapshot GetLastSessionSnapshot() const override;
300 base::Value* GetTypeStatusMap() const override;
301 const GURL& sync_service_url() const override;
302 std::string unrecoverable_error_message() const override;
303 tracked_objects::Location unrecoverable_error_location() const override;
305 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer);
306 void RemoveProtocolEventObserver(
307 browser_sync::ProtocolEventObserver* observer);
309 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
310 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer);
312 // Add a sync type preference provider. Each provider may only be added once.
313 void AddPreferenceProvider(SyncTypePreferenceProvider* provider);
314 // Remove a sync type preference provider. May only be called for providers
315 // that have been added. Providers must not remove themselves while being
316 // called back.
317 void RemovePreferenceProvider(SyncTypePreferenceProvider* provider);
318 // Check whether a given sync type preference provider has been added.
319 bool HasPreferenceProvider(SyncTypePreferenceProvider* provider) const;
321 // Asynchronously fetches base::Value representations of all sync nodes and
322 // returns them to the specified callback on this thread.
324 // These requests can live a long time and return when you least expect it.
325 // For safety, the callback should be bound to some sort of WeakPtr<> or
326 // scoped_refptr<>.
327 void GetAllNodes(
328 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
330 void RegisterAuthNotifications();
331 void UnregisterAuthNotifications();
333 // Return whether OAuth2 refresh token is loaded and available for the backend
334 // to start up. Virtual to enable mocking in tests.
335 virtual bool IsOAuthRefreshTokenAvailable();
337 // Registers a type whose sync storage will not be managed by the
338 // ProfileSyncService. It declares that this sync type may be activated at
339 // some point in the future. This function call does not enable or activate
340 // the syncing of this type
341 // TODO(stanisc): crbug.com/515962: this should merge with
342 // RegisterDataTypeController.
343 void RegisterNonBlockingType(syncer::ModelType type);
345 // Called by a component that supports non-blocking sync when it is ready to
346 // initialize its connection to the sync backend.
348 // If policy allows for syncing this type (ie. it is "preferred"), then this
349 // should result in a message to enable syncing for this type when the sync
350 // backend is available. If the type is not to be synced, this should result
351 // in a message that allows the component to delete its local sync state.
352 // TODO(stanisc): crbug.com/515962: review usage of this.
353 void InitializeNonBlockingType(
354 syncer::ModelType type,
355 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
356 const base::WeakPtr<syncer_v2::ModelTypeProcessorImpl>& type_processor);
358 // Returns the SyncedWindowDelegatesGetter from the embedded sessions manager.
359 virtual browser_sync::SyncedWindowDelegatesGetter*
360 GetSyncedWindowDelegatesGetter() const;
362 // Returns the SyncableService for syncer::SESSIONS.
363 virtual syncer::SyncableService* GetSessionsSyncableService();
365 // Returns the SyncableService for syncer::DEVICE_INFO.
366 virtual syncer::SyncableService* GetDeviceInfoSyncableService();
368 // Returns synced devices tracker.
369 virtual sync_driver::DeviceInfoTracker* GetDeviceInfoTracker() const;
371 // Fills state_map with a map of current data types that are possible to
372 // sync, as well as their states.
373 void GetDataTypeControllerStates(
374 sync_driver::DataTypeController::StateMap* state_map) const;
376 // SyncFrontend implementation.
377 void OnBackendInitialized(
378 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
379 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
380 debug_info_listener,
381 const std::string& cache_guid,
382 bool success) override;
383 void OnSyncCycleCompleted() override;
384 void OnProtocolEvent(const syncer::ProtocolEvent& event) override;
385 void OnDirectoryTypeCommitCounterUpdated(
386 syncer::ModelType type,
387 const syncer::CommitCounters& counters) override;
388 void OnDirectoryTypeUpdateCounterUpdated(
389 syncer::ModelType type,
390 const syncer::UpdateCounters& counters) override;
391 void OnDirectoryTypeStatusCounterUpdated(
392 syncer::ModelType type,
393 const syncer::StatusCounters& counters) override;
394 void OnConnectionStatusChange(syncer::ConnectionStatus status) override;
395 void OnPassphraseRequired(
396 syncer::PassphraseRequiredReason reason,
397 const sync_pb::EncryptedData& pending_keys) override;
398 void OnPassphraseAccepted() override;
399 void OnEncryptedTypesChanged(syncer::ModelTypeSet encrypted_types,
400 bool encrypt_everything) override;
401 void OnEncryptionComplete() override;
402 void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override;
403 void OnExperimentsChanged(const syncer::Experiments& experiments) override;
404 void OnActionableError(const syncer::SyncProtocolError& error) override;
405 void OnLocalSetPassphraseEncryption(
406 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) override;
408 // DataTypeManagerObserver implementation.
409 void OnConfigureDone(
410 const sync_driver::DataTypeManager::ConfigureResult& result) override;
411 void OnConfigureStart() override;
413 // DataTypeEncryptionHandler implementation.
414 bool IsPassphraseRequired() const override;
415 syncer::ModelTypeSet GetEncryptedDataTypes() const override;
417 // SigninManagerBase::Observer implementation.
418 void GoogleSigninSucceeded(const std::string& account_id,
419 const std::string& username,
420 const std::string& password) override;
421 void GoogleSignedOut(const std::string& account_id,
422 const std::string& username) override;
424 // Get the sync status code.
425 SyncStatusSummary QuerySyncStatusSummary();
427 // Reconfigures the data type manager with the latest enabled types.
428 // Note: Does not initialize the backend if it is not already initialized.
429 // This function needs to be called only after sync has been initialized
430 // (i.e.,only for reconfigurations). The reason we don't initialize the
431 // backend is because if we had encountered an unrecoverable error we don't
432 // want to startup once more.
433 // This function is called by |SetSetupInProgress|.
434 virtual void ReconfigureDatatypeManager();
436 syncer::PassphraseRequiredReason passphrase_required_reason() const {
437 return passphrase_required_reason_;
440 // Returns true if sync is requested to be running by the user.
441 // Note that this does not mean that sync WILL be running; e.g. if
442 // IsSyncAllowed() is false then sync won't start, and if the user
443 // doesn't confirm their settings (HasSyncSetupCompleted), sync will
444 // never become active. Use IsSyncActive to see if sync is running.
445 virtual bool IsSyncRequested() const;
447 sync_driver::SyncApiComponentFactory* factory() const {
448 return factory_.get();
451 // The profile we are syncing for.
452 Profile* profile() const { return profile_; }
454 // Returns a weak pointer to the service's JsController.
455 // Overrideable for testing purposes.
456 virtual base::WeakPtr<syncer::JsController> GetJsController();
458 // Record stats on various events.
459 static void SyncEvent(SyncEventCodes code);
461 // Returns whether sync is allowed to run based on command-line switches.
462 // Profile::IsSyncAllowed() is probably a better signal than this function.
463 // This function can be called from any thread, and the implementation doesn't
464 // assume it's running on the UI thread.
465 static bool IsSyncAllowedByFlag();
467 // Returns whether sync is managed, i.e. controlled by configuration
468 // management. If so, the user is not allowed to configure sync.
469 virtual bool IsManaged() const;
471 // syncer::UnrecoverableErrorHandler implementation.
472 void OnUnrecoverableError(const tracked_objects::Location& from_here,
473 const std::string& message) override;
475 // The functions below (until ActivateDataType()) should only be
476 // called if backend_initialized() is true.
478 // TODO(akalin): These two functions are used only by
479 // ProfileSyncServiceHarness. Figure out a different way to expose
480 // this info to that class, and remove these functions.
482 // Returns whether or not the underlying sync engine has made any
483 // local changes to items that have not yet been synced with the
484 // server.
485 bool HasUnsyncedItems() const;
487 // Used by ProfileSyncServiceHarness. May return NULL.
488 browser_sync::BackendMigrator* GetBackendMigratorForTest();
490 // Used by tests to inspect interaction with OAuth2TokenService.
491 bool IsRetryingAccessTokenFetchForTest() const;
493 // Used by tests to inspect the OAuth2 access tokens used by PSS.
494 std::string GetAccessTokenForTest() const;
496 // TODO(sync): This is only used in tests. Can we remove it?
497 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const;
499 // SyncPrefObserver implementation.
500 void OnSyncManagedPrefChange(bool is_sync_managed) override;
502 // Changes which data types we're going to be syncing to |preferred_types|.
503 // If it is running, the DataTypeManager will be instructed to reconfigure
504 // the sync backend so that exactly these datatypes are actively synced. See
505 // class comment for more on what it means for a datatype to be Preferred.
506 virtual void ChangePreferredDataTypes(
507 syncer::ModelTypeSet preferred_types);
509 // Returns the set of directory types which are preferred for enabling.
510 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const;
512 // Returns the set of off-thread types which are preferred for enabling.
513 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const;
515 // Returns the set of types which are enforced programmatically and can not
516 // be disabled by the user.
517 virtual syncer::ModelTypeSet GetForcedDataTypes() const;
519 // Gets the set of all data types that could be allowed (the set that
520 // should be advertised to the user). These will typically only change
521 // via a command-line option. See class comment for more on what it means
522 // for a datatype to be Registered.
523 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const;
525 // Gets the set of directory types which could be allowed.
526 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const;
528 // Gets the set of off-thread types which could be allowed.
529 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const;
531 // Returns the actual passphrase type being used for encryption.
532 virtual syncer::PassphraseType GetPassphraseType() const;
534 // Note about setting passphrases: There are different scenarios under which
535 // we might want to apply a passphrase. It could be for first-time encryption,
536 // re-encryption, or for decryption by clients that sign in at a later time.
537 // In addition, encryption can either be done using a custom passphrase, or by
538 // reusing the GAIA password. Depending on what is happening in the system,
539 // callers should determine which of the two methods below must be used.
541 // Returns true if encrypting all the sync data is allowed. If this method
542 // returns false, EnableEncryptEverything() should not be called.
543 virtual bool EncryptEverythingAllowed() const;
545 // Sets whether encrypting all the sync data is allowed or not.
546 virtual void SetEncryptEverythingAllowed(bool allowed);
548 // Returns true if the syncer is waiting for new datatypes to be encrypted.
549 virtual bool encryption_pending() const;
551 SigninManagerBase* signin() const;
553 // Used by tests.
554 bool auto_start_enabled() const;
556 SyncErrorController* sync_error_controller() {
557 return sync_error_controller_.get();
560 // TODO(sync): This is only used in tests. Can we remove it?
561 const sync_driver::DataTypeStatusTable& data_type_status_table() const;
563 sync_driver::DataTypeManager::ConfigureStatus configure_status() {
564 return configure_status_;
567 // If true, the ProfileSyncService has detected that a new GAIA signin has
568 // succeeded, and is waiting for initialization to complete. This is used by
569 // the UI to differentiate between a new auth error (encountered as part of
570 // the initialization process) and a pre-existing auth error that just hasn't
571 // been cleared yet. Virtual for testing purposes.
572 virtual bool waiting_for_auth() const;
574 // The set of currently enabled sync experiments.
575 const syncer::Experiments& current_experiments() const;
577 // OAuth2TokenService::Consumer implementation.
578 void OnGetTokenSuccess(const OAuth2TokenService::Request* request,
579 const std::string& access_token,
580 const base::Time& expiration_time) override;
581 void OnGetTokenFailure(const OAuth2TokenService::Request* request,
582 const GoogleServiceAuthError& error) override;
584 // OAuth2TokenService::Observer implementation.
585 void OnRefreshTokenAvailable(const std::string& account_id) override;
586 void OnRefreshTokenRevoked(const std::string& account_id) override;
587 void OnRefreshTokensLoaded() override;
589 // KeyedService implementation. This must be called exactly
590 // once (before this object is destroyed).
591 void Shutdown() override;
593 browser_sync::FaviconCache* GetFaviconCache();
595 // Overrides the NetworkResources used for Sync connections.
596 // This function takes ownership of |network_resources|.
597 void OverrideNetworkResourcesForTest(
598 scoped_ptr<syncer::NetworkResources> network_resources);
600 virtual bool IsDataTypeControllerRunning(syncer::ModelType type) const;
602 // Returns the current mode the backend is in.
603 BackendMode backend_mode() const;
605 // Helpers for testing rollback.
606 void SetBrowsingDataRemoverObserverForTesting(
607 BrowsingDataRemover::Observer* observer);
608 void SetClearingBrowseringDataForTesting(base::Callback<
609 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
612 base::Time GetDeviceBackupTimeForTesting() const;
614 // This triggers a Directory::SaveChanges() call on the sync thread.
615 // It should be used to persist data to disk when the process might be
616 // killed in the near future.
617 void FlushDirectory() const;
619 // Needed to test whether the directory is deleted properly.
620 base::FilePath GetDirectoryPathForTest() const;
622 // Sometimes we need to wait for tasks on the sync thread in tests.
623 base::MessageLoop* GetSyncLoopForTest() const;
625 // Triggers sync cycle with request to update specified |types|.
626 void RefreshTypesForTest(syncer::ModelTypeSet types);
628 protected:
629 // Helper to install and configure a data type manager.
630 void ConfigureDataTypeManager();
632 // Shuts down the backend sync components.
633 // |reason| dictates if syncing is being disabled or not, and whether
634 // to claim ownership of sync thread from backend.
635 void ShutdownImpl(syncer::ShutdownReason reason);
637 // Return SyncCredentials from the OAuth2TokenService.
638 syncer::SyncCredentials GetCredentials();
640 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler();
642 const sync_driver::DataTypeController::TypeMap&
643 directory_data_type_controllers() {
644 return directory_data_type_controllers_;
647 // Helper method for managing encryption UI.
648 bool IsEncryptedDatatypeEnabled() const;
650 // Helper for OnUnrecoverableError.
651 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl,
652 // and in SyncBackendHost::Shutdown.
653 void OnUnrecoverableErrorImpl(
654 const tracked_objects::Location& from_here,
655 const std::string& message,
656 bool delete_sync_database);
658 virtual bool NeedBackup() const;
660 // This is a cache of the last authentication response we received from the
661 // sync server. The UI queries this to display appropriate messaging to the
662 // user.
663 GoogleServiceAuthError last_auth_error_;
665 // Our asynchronous backend to communicate with sync components living on
666 // other threads.
667 scoped_ptr<browser_sync::SyncBackendHost> backend_;
669 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it
670 // was required for encryption, decryption with a cached passphrase, or
671 // because a new passphrase is required?
672 syncer::PassphraseRequiredReason passphrase_required_reason_;
674 private:
675 enum UnrecoverableErrorReason {
676 ERROR_REASON_UNSET,
677 ERROR_REASON_SYNCER,
678 ERROR_REASON_BACKEND_INIT_FAILURE,
679 ERROR_REASON_CONFIGURATION_RETRY,
680 ERROR_REASON_CONFIGURATION_FAILURE,
681 ERROR_REASON_ACTIONABLE_ERROR,
682 ERROR_REASON_LIMIT
685 enum AuthErrorMetric {
686 AUTH_ERROR_ENCOUNTERED,
687 AUTH_ERROR_FIXED,
688 AUTH_ERROR_LIMIT
691 friend class ProfileSyncServicePasswordTest;
692 friend class SyncTest;
693 friend class TestProfileSyncService;
694 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState);
696 // Stops the sync engine. Does NOT set IsSyncRequested to false. Use
697 // RequestStop for that. |data_fate| controls whether the local sync data is
698 // deleted or kept when the engine shuts down.
699 void StopImpl(SyncStopDataFate data_fate);
701 // Update the last auth error and notify observers of error state.
702 void UpdateAuthErrorState(const GoogleServiceAuthError& error);
704 // Detects and attempts to recover from a previous improper datatype
705 // configuration where Keep Everything Synced and the preferred types were
706 // not correctly set.
707 void TrySyncDatatypePrefRecovery();
709 // Puts the backend's sync scheduler into NORMAL mode.
710 // Called when configuration is complete.
711 void StartSyncingWithServer();
713 // Called when we've determined that we don't need a passphrase (either
714 // because OnPassphraseAccepted() was called, or because we've gotten a
715 // OnPassphraseRequired() but no data types are enabled).
716 void ResolvePassphraseRequired();
718 // During initial signin, ProfileSyncService caches the user's signin
719 // passphrase so it can be used to encrypt/decrypt data after sync starts up.
720 // This routine is invoked once the backend has started up to use the
721 // cached passphrase and clear it out when it is done.
722 void ConsumeCachedPassphraseIfPossible();
724 // RequestAccessToken initiates RPC to request downscoped access token from
725 // refresh token. This happens when a new OAuth2 login token is loaded and
726 // when sync server returns AUTH_ERROR which indicates it is time to refresh
727 // token.
728 virtual void RequestAccessToken();
730 // Return true if backend should start from a fresh sync DB.
731 bool ShouldDeleteSyncFolder();
733 // If |delete_sync_data_folder| is true, then this method will delete all
734 // previous "Sync Data" folders. (useful if the folder is partial/corrupt).
735 void InitializeBackend(bool delete_sync_data_folder);
737 // Initializes the various settings from the command line.
738 void InitSettings();
740 // Sets the last synced time to the current time.
741 void UpdateLastSyncedTime();
743 void NotifyObservers();
744 void NotifySyncCycleCompleted();
746 void ClearStaleErrors();
748 void ClearUnrecoverableError();
750 // Starts up the backend sync components. |mode| specifies the kind of
751 // backend to start, one of SYNC, BACKUP or ROLLBACK.
752 virtual void StartUpSlowBackendComponents(BackendMode mode);
754 // Collects preferred sync data types from |preference_providers_|.
755 syncer::ModelTypeSet GetDataTypesFromPreferenceProviders() const;
757 // Called when the user changes the sync configuration, to update the UMA
758 // stats.
759 void UpdateSelectedTypesHistogram(
760 bool sync_everything,
761 const syncer::ModelTypeSet chosen_types) const;
763 #if defined(OS_CHROMEOS)
764 // Refresh spare sync bootstrap token for re-enabling the sync service.
765 // Called on successful sign-in notifications.
766 void RefreshSpareBootstrapToken(const std::string& passphrase);
767 #endif
769 // Internal unrecoverable error handler. Used to track error reason via
770 // Sync.UnrecoverableErrors histogram.
771 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here,
772 const std::string& message,
773 bool delete_sync_database,
774 UnrecoverableErrorReason reason);
776 // Returns the type of manager to use according to |backend_mode_|.
777 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const;
779 // Update UMA for syncing backend.
780 void UpdateBackendInitUMA(bool success);
782 // Various setup following backend initialization, mostly for syncing backend.
783 void PostBackendInitialization();
785 // Whether sync has been authenticated with an account ID.
786 bool IsSignedIn() const;
788 // True if a syncing backend exists.
789 bool HasSyncingBackend() const;
791 // Update first sync time stored in preferences
792 void UpdateFirstSyncTimePref();
794 // Clear browsing data since first sync during rollback.
795 void ClearBrowsingDataSinceFirstSync();
797 // Post background task to check sync backup DB state if needed.
798 void CheckSyncBackupIfNeeded();
800 // Callback to receive backup DB check result.
801 void CheckSyncBackupCallback(base::Time backup_time);
803 // Callback function to call |startup_controller_|.TryStart() after
804 // backup/rollback finishes;
805 void TryStartSyncAfterBackup();
807 // Clean up prefs and backup DB when rollback is not needed.
808 void CleanUpBackup();
810 // Tell the sync server that this client has disabled sync.
811 void RemoveClientFromServer() const;
813 // Called when the system is under memory pressure.
814 void OnMemoryPressure(
815 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
817 // Check if previous shutdown is shutdown cleanly.
818 void ReportPreviousSessionMemoryWarningCount();
820 // After user switches to custom passphrase encryption a set of steps needs to
821 // be performed:
822 // - Download all latest updates from server (catch up configure).
823 // - Clear user data on server.
824 // - Clear directory so that data is merged from model types and encrypted.
825 // Following three functions perform these steps.
827 // Calls data type manager to start catch up configure.
828 void BeginConfigureCatchUpBeforeClear();
830 // Calls sync backend to send ClearServerDataMessage to server.
831 void ClearAndRestartSyncForPassphraseEncryption();
833 // Restarts sync clearing directory in the process.
834 void OnClearServerDataDone();
836 // Factory used to create various dependent objects.
837 scoped_ptr<sync_driver::SyncApiComponentFactory> factory_;
839 // The profile whose data we are synchronizing.
840 Profile* profile_;
842 // The class that handles getting, setting, and persisting sync
843 // preferences.
844 sync_driver::SyncPrefs sync_prefs_;
846 // TODO(ncarter): Put this in a profile, once there is UI for it.
847 // This specifies where to find the sync server.
848 const GURL sync_service_url_;
850 // The time that OnConfigureStart is called. This member is zero if
851 // OnConfigureStart has not yet been called, and is reset to zero once
852 // OnConfigureDone is called.
853 base::Time sync_configure_start_time_;
855 // Indicates if this is the first time sync is being configured. This value
856 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized().
857 bool is_first_time_sync_configure_;
859 // List of available data type controllers for directory types.
860 sync_driver::DataTypeController::TypeMap directory_data_type_controllers_;
862 // Whether the SyncBackendHost has been initialized.
863 bool backend_initialized_;
865 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents
866 // ProfileSyncService from starting backend till browser restarted or user
867 // signed out.
868 bool sync_disabled_by_admin_;
870 // Set to true if a signin has completed but we're still waiting for the
871 // backend to refresh its credentials.
872 bool is_auth_in_progress_;
874 // Encapsulates user signin - used to set/get the user's authenticated
875 // email address.
876 const scoped_ptr<SigninManagerWrapper> signin_;
878 // Information describing an unrecoverable error.
879 UnrecoverableErrorReason unrecoverable_error_reason_;
880 std::string unrecoverable_error_message_;
881 tracked_objects::Location unrecoverable_error_location_;
883 // Manages the start and stop of the directory data types.
884 scoped_ptr<sync_driver::DataTypeManager> directory_data_type_manager_;
886 // Manager for the non-blocking data types.
887 sync_driver_v2::NonBlockingDataTypeManager non_blocking_data_type_manager_;
889 base::ObserverList<sync_driver::SyncServiceObserver> observers_;
890 base::ObserverList<browser_sync::ProtocolEventObserver>
891 protocol_event_observers_;
892 base::ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_;
894 std::set<SyncTypePreferenceProvider*> preference_providers_;
896 syncer::SyncJsController sync_js_controller_;
898 // This allows us to gracefully handle an ABORTED return code from the
899 // DataTypeManager in the event that the server informed us to cease and
900 // desist syncing immediately.
901 bool expect_sync_configuration_aborted_;
903 // Sometimes we need to temporarily hold on to a passphrase because we don't
904 // yet have a backend to send it to. This happens during initialization as
905 // we don't StartUp until we have a valid token, which happens after valid
906 // credentials were provided.
907 std::string cached_passphrase_;
909 // The current set of encrypted types. Always a superset of
910 // syncer::Cryptographer::SensitiveTypes().
911 syncer::ModelTypeSet encrypted_types_;
913 // Whether encrypting everything is allowed.
914 bool encrypt_everything_allowed_;
916 // Whether we want to encrypt everything.
917 bool encrypt_everything_;
919 // Whether we're waiting for an attempt to encryption all sync data to
920 // complete. We track this at this layer in order to allow the user to cancel
921 // if they e.g. don't remember their explicit passphrase.
922 bool encryption_pending_;
924 scoped_ptr<browser_sync::BackendMigrator> migrator_;
926 // This is the last |SyncProtocolError| we received from the server that had
927 // an action set on it.
928 syncer::SyncProtocolError last_actionable_error_;
930 // Exposes sync errors to the UI.
931 scoped_ptr<SyncErrorController> sync_error_controller_;
933 // Tracks the set of failed data types (those that encounter an error
934 // or must delay loading for some reason).
935 sync_driver::DataTypeStatusTable data_type_status_table_;
937 sync_driver::DataTypeManager::ConfigureStatus configure_status_;
939 // The set of currently enabled sync experiments.
940 syncer::Experiments current_experiments_;
942 // Sync's internal debug info listener. Used to record datatype configuration
943 // and association information.
944 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
946 // A thread where all the sync operations happen.
947 // OWNERSHIP Notes:
948 // * Created when backend starts for the first time.
949 // * If sync is disabled, PSS claims ownership from backend.
950 // * If sync is reenabled, PSS passes ownership to new backend.
951 scoped_ptr<base::Thread> sync_thread_;
953 // ProfileSyncService uses this service to get access tokens.
954 ProfileOAuth2TokenService* const oauth2_token_service_;
956 // ProfileSyncService needs to remember access token in order to invalidate it
957 // with OAuth2TokenService.
958 std::string access_token_;
960 // ProfileSyncService needs to hold reference to access_token_request_ for
961 // the duration of request in order to receive callbacks.
962 scoped_ptr<OAuth2TokenService::Request> access_token_request_;
964 // If RequestAccessToken fails with transient error then retry requesting
965 // access token with exponential backoff.
966 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_;
967 net::BackoffEntry request_access_token_backoff_;
969 // States related to sync token and connection.
970 base::Time connection_status_update_time_;
971 syncer::ConnectionStatus connection_status_;
972 base::Time token_request_time_;
973 base::Time token_receive_time_;
974 GoogleServiceAuthError last_get_token_error_;
975 base::Time next_token_request_time_;
977 scoped_ptr<sync_driver::LocalDeviceInfoProvider> local_device_;
979 // Locally owned SyncableService implementations.
980 scoped_ptr<browser_sync::SessionsSyncManager> sessions_sync_manager_;
981 scoped_ptr<sync_driver::DeviceInfoSyncService> device_info_sync_service_;
983 scoped_ptr<syncer::NetworkResources> network_resources_;
985 scoped_ptr<browser_sync::StartupController> startup_controller_;
987 scoped_ptr<browser_sync::BackupRollbackController>
988 backup_rollback_controller_;
990 // Mode of current backend.
991 BackendMode backend_mode_;
993 // Whether backup is needed before sync starts.
994 bool need_backup_;
996 // Whether backup is finished.
997 bool backup_finished_;
999 base::Time backup_start_time_;
1001 base::Callback<
1002 void(BrowsingDataRemover::Observer*, Profile*, base::Time, base::Time)>
1003 clear_browsing_data_;
1005 // Last time when pre-sync data was saved. NULL pointer means backup data
1006 // state is unknown. If time value is null, backup data doesn't exist.
1007 scoped_ptr<base::Time> last_backup_time_;
1009 BrowsingDataRemover::Observer* browsing_data_remover_observer_;
1011 // The full path to the sync data directory.
1012 base::FilePath directory_path_;
1014 scoped_ptr<browser_sync::SyncStoppedReporter> sync_stopped_reporter_;
1016 // Listens for the system being under memory pressure.
1017 scoped_ptr<base::MemoryPressureListener> memory_pressure_listener_;
1019 // Nigori state after user switching to custom passphrase, saved until
1020 // transition steps complete. It will be injected into new backend after sync
1021 // restart.
1022 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state_;
1024 // When BeginConfigureCatchUpBeforeClear is called it will set
1025 // catch_up_configure_in_progress_ to true. This is needed to detect that call
1026 // to OnConfigureDone originated from BeginConfigureCatchUpBeforeClear and
1027 // needs to be followed by ClearAndRestartSyncForPassphraseEncryption().
1028 bool catch_up_configure_in_progress_;
1030 // Whether the major version has changed since the last time Chrome ran,
1031 // and therefore a passphrase required state should result in prompting
1032 // the user. This logic is only enabled on platforms that consume the
1033 // IsPassphrasePrompted sync preference.
1034 bool passphrase_prompt_triggered_by_version_;
1036 base::WeakPtrFactory<ProfileSyncService> weak_factory_;
1038 // We don't use |weak_factory_| for the StartupController because the weak
1039 // ptrs should be bound to the lifetime of ProfileSyncService and not to the
1040 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass
1041 // StartupController an Unretained reference to future-proof against
1042 // the controller impl changing to post tasks. Therefore, we have a separate
1043 // factory.
1044 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_;
1046 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService);
1049 bool ShouldShowActionOnUI(
1050 const syncer::SyncProtocolError& error);
1053 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_