1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 7 8 #include <string> 9 #include <utility> 10 #include <vector> 11 12 #include "base/basictypes.h" 13 #include "base/compiler_specific.h" 14 #include "base/gtest_prod_util.h" 15 #include "base/location.h" 16 #include "base/memory/scoped_ptr.h" 17 #include "base/memory/scoped_vector.h" 18 #include "base/memory/weak_ptr.h" 19 #include "base/observer_list.h" 20 #include "base/strings/string16.h" 21 #include "base/time/time.h" 22 #include "base/timer/timer.h" 23 #include "chrome/browser/signin/oauth2_token_service.h" 24 #include "chrome/browser/signin/signin_global_error.h" 25 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h" 26 #include "chrome/browser/sync/glue/data_type_controller.h" 27 #include "chrome/browser/sync/glue/data_type_encryption_handler.h" 28 #include "chrome/browser/sync/glue/data_type_manager.h" 29 #include "chrome/browser/sync/glue/data_type_manager_observer.h" 30 #include "chrome/browser/sync/glue/failed_data_types_handler.h" 31 #include "chrome/browser/sync/glue/sync_backend_host.h" 32 #include "chrome/browser/sync/profile_sync_service_base.h" 33 #include "chrome/browser/sync/profile_sync_service_observer.h" 34 #include "chrome/browser/sync/sync_prefs.h" 35 #include "components/browser_context_keyed_service/browser_context_keyed_service.h" 36 #include "content/public/browser/notification_observer.h" 37 #include "content/public/browser/notification_registrar.h" 38 #include "content/public/browser/notification_types.h" 39 #include "google_apis/gaia/google_service_auth_error.h" 40 #include "net/base/backoff_entry.h" 41 #include "sync/internal_api/public/base/model_type.h" 42 #include "sync/internal_api/public/engine/model_safe_worker.h" 43 #include "sync/internal_api/public/sync_manager_factory.h" 44 #include "sync/internal_api/public/util/experiments.h" 45 #include "sync/internal_api/public/util/unrecoverable_error_handler.h" 46 #include "sync/js/sync_js_controller.h" 47 #include "url/gurl.h" 48 49 class Profile; 50 class ProfileSyncComponentsFactory; 51 class SigninManagerBase; 52 class SyncGlobalError; 53 54 namespace browser_sync { 55 class BackendMigrator; 56 class ChangeProcessor; 57 class DeviceInfo; 58 class DataTypeManager; 59 class JsController; 60 class SessionModelAssociator; 61 62 namespace sessions { class SyncSessionSnapshot; } 63 } 64 65 namespace syncer { 66 class BaseTransaction; 67 struct SyncCredentials; 68 struct UserShare; 69 } 70 71 namespace sync_pb { 72 class EncryptedData; 73 } // namespace sync_pb 74 75 // ProfileSyncService is the layer between browser subsystems like bookmarks, 76 // and the sync backend. Each subsystem is logically thought of as being 77 // a sync datatype. 78 // 79 // Individual datatypes can, at any point, be in a variety of stages of being 80 // "enabled". Here are some specific terms for concepts used in this class: 81 // 82 // 'Registered' (feature suppression for a datatype) 83 // 84 // When a datatype is registered, the user has the option of syncing it. 85 // The sync opt-in UI will show only registered types; a checkbox should 86 // never be shown for an unregistered type, and nor should it ever be 87 // synced. 88 // 89 // A datatype is considered registered once RegisterDataTypeController 90 // has been called with that datatype's DataTypeController. 91 // 92 // 'Preferred' (user preferences and opt-out for a datatype) 93 // 94 // This means the user's opt-in or opt-out preference on a per-datatype 95 // basis. The sync service will try to make active exactly these types. 96 // If a user has opted out of syncing a particular datatype, it will 97 // be registered, but not preferred. 98 // 99 // This state is controlled by the ConfigurePreferredDataTypes and 100 // GetPreferredDataTypes. They are stored in the preferences system, 101 // and persist; though if a datatype is not registered, it cannot 102 // be a preferred datatype. 103 // 104 // 'Active' (run-time initialization of sync system for a datatype) 105 // 106 // An active datatype is a preferred datatype that is actively being 107 // synchronized: the syncer has been instructed to querying the server 108 // for this datatype, first-time merges have finished, and there is an 109 // actively installed ChangeProcessor that listens for changes to this 110 // datatype, propagating such changes into and out of the sync backend 111 // as necessary. 112 // 113 // When a datatype is in the process of becoming active, it may be 114 // in some intermediate state. Those finer-grained intermediate states 115 // are differentiated by the DataTypeController state. 116 // 117 // Sync Configuration: 118 // 119 // Sync configuration is accomplished via the following APIs: 120 // * OnUserChoseDatatypes(): Set the data types the user wants to sync. 121 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data 122 // using the passed passphrase. 123 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed 124 // passphrase. 125 // 126 // Additionally, the current sync configuration can be fetched by calling 127 // * GetRegisteredDataTypes() 128 // * GetPreferredDataTypes() 129 // * GetActiveDataTypes() 130 // * IsUsingSecondaryPassphrase() 131 // * EncryptEverythingEnabled() 132 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption() 133 // 134 // The "sync everything" state cannot be read from ProfileSyncService, but 135 // is instead pulled from SyncPrefs.HasKeepEverythingSynced(). 136 // 137 // Initial sync setup: 138 // 139 // For privacy reasons, it is usually desirable to avoid syncing any data 140 // types until the user has finished setting up sync. There are two APIs 141 // that control the initial sync download: 142 // 143 // * SetSyncSetupCompleted() 144 // * SetSetupInProgress() 145 // 146 // SetSyncSetupCompleted() should be called once the user has finished setting 147 // up sync at least once on their account. SetSetupInProgress(true) should be 148 // called while the user is actively configuring their account, and then 149 // SetSetupInProgress(false) should be called when configuration is complete. 150 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has 151 // been called, then the sync engine knows not to download any user data. 152 // 153 // When initial sync is complete, the UI code should call 154 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will 155 // tell the sync engine that setup is completed and it can begin downloading 156 // data from the sync server. 157 // 158 class ProfileSyncService : public ProfileSyncServiceBase, 159 public browser_sync::SyncFrontend, 160 public browser_sync::SyncPrefObserver, 161 public browser_sync::DataTypeManagerObserver, 162 public SigninGlobalError::AuthStatusProvider, 163 public syncer::UnrecoverableErrorHandler, 164 public content::NotificationObserver, 165 public BrowserContextKeyedService, 166 public browser_sync::DataTypeEncryptionHandler, 167 public OAuth2TokenService::Consumer, 168 public OAuth2TokenService::Observer { 169 public: 170 typedef browser_sync::SyncBackendHost::Status Status; 171 172 enum SyncEventCodes { 173 MIN_SYNC_EVENT_CODE = 0, 174 175 // Events starting the sync service. 176 START_FROM_NTP = 1, // Sync was started from the ad in NTP 177 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu. 178 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options. 179 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager. 180 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu. 181 START_FROM_URL = 6, // Sync was started from a typed URL. 182 183 // Events regarding cancellation of the signon process of sync. 184 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting 185 // username and password. 186 CANCEL_DURING_SIGNON = 11, // Cancelled after auth. 187 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data 188 // types and clicking OK. 189 // Events resulting in the stoppage of sync service. 190 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options. 191 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings. 192 193 // Miscellaneous events caused by sync service. 194 195 MAX_SYNC_EVENT_CODE 196 }; 197 198 // Defines the type of behavior the sync engine should use. If configured for 199 // AUTO_START, the sync engine will automatically call SetSyncSetupCompleted() 200 // and start downloading data types as soon as sync credentials are available 201 // (a signed-in username and a "chromiumsync" token). 202 // If configured for MANUAL_START, sync will not start until the user 203 // completes sync setup, at which point the UI makes an explicit call to 204 // SetSyncSetupCompleted(). 205 enum StartBehavior { 206 AUTO_START, 207 MANUAL_START, 208 }; 209 210 // Used to specify the kind of passphrase with which sync data is encrypted. 211 enum PassphraseType { 212 IMPLICIT, // The user did not provide a custom passphrase for encryption. 213 // We implicitly use the GAIA password in such cases. 214 EXPLICIT, // The user selected the "use custom passphrase" radio button 215 // during sync setup and provided a passphrase. 216 }; 217 218 // Default sync server URL. 219 static const char* kSyncServerUrl; 220 // Sync server URL for dev channel users 221 static const char* kDevServerUrl; 222 223 // Takes ownership of |factory|. 224 ProfileSyncService(ProfileSyncComponentsFactory* factory, 225 Profile* profile, 226 SigninManagerBase* signin, 227 StartBehavior start_behavior); 228 virtual ~ProfileSyncService(); 229 230 // Initializes the object. This must be called at most once, and 231 // immediately after an object of this class is constructed. 232 void Initialize(); 233 234 virtual void SetSyncSetupCompleted(); 235 236 // ProfileSyncServiceBase implementation. 237 virtual bool HasSyncSetupCompleted() const OVERRIDE; 238 virtual bool ShouldPushChanges() OVERRIDE; 239 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE; 240 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE; 241 virtual void RemoveObserver( 242 ProfileSyncServiceBase::Observer* observer) OVERRIDE; 243 virtual bool HasObserver( 244 ProfileSyncServiceBase::Observer* observer) const OVERRIDE; 245 246 void RegisterAuthNotifications(); 247 void UnregisterAuthNotifications(); 248 249 // Returns true if sync is enabled/not suppressed and the user is logged in. 250 // (being logged in does not mean that tokens are available - tokens may 251 // be missing because they have not loaded yet, or because they were deleted 252 // due to http://crbug.com/121755). 253 // Virtual to enable mocking in tests. 254 virtual bool IsSyncEnabledAndLoggedIn(); 255 256 // Return whether OAuth2 refresh token is loaded and available for the backend 257 // to start up. Virtual to enable mocking in tests. 258 virtual bool IsOAuthRefreshTokenAvailable(); 259 260 // Registers a data type controller with the sync service. This 261 // makes the data type controller available for use, it does not 262 // enable or activate the synchronization of the data type (see 263 // ActivateDataType). Takes ownership of the pointer. 264 void RegisterDataTypeController( 265 browser_sync::DataTypeController* data_type_controller); 266 267 // Returns the session model associator associated with this type, but only if 268 // the associator is running. If it is doing anything else, it will return 269 // null. 270 // TODO(zea): Figure out a better way to expose this to the UI elements that 271 // need it. 272 browser_sync::SessionModelAssociator* GetSessionModelAssociator(); 273 274 // Returns sync's representation of the local device info. 275 // Return value is an empty scoped_ptr if the device info is unavailable. 276 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo() const; 277 278 // Returns sync's representation of the device info for a client identified 279 // by |client_id|. Return value is an empty scoped ptr if the device info 280 // is unavailable. 281 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo( 282 const std::string& client_id) const; 283 284 // Gets the device info for all devices signed into the account associated 285 // with this profile. 286 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const; 287 288 // Fills state_map with a map of current data types that are possible to 289 // sync, as well as their states. 290 void GetDataTypeControllerStates( 291 browser_sync::DataTypeController::StateMap* state_map) const; 292 293 // Disables sync for user. Use ShowLoginDialog to enable. 294 virtual void DisableForUser(); 295 296 // SyncFrontend implementation. 297 virtual void OnBackendInitialized( 298 const syncer::WeakHandle<syncer::JsBackend>& js_backend, 299 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>& 300 debug_info_listener, 301 bool success) OVERRIDE; 302 virtual void OnSyncCycleCompleted() OVERRIDE; 303 virtual void OnSyncConfigureRetry() OVERRIDE; 304 virtual void OnConnectionStatusChange( 305 syncer::ConnectionStatus status) OVERRIDE; 306 virtual void OnStopSyncingPermanently() OVERRIDE; 307 virtual void OnPassphraseRequired( 308 syncer::PassphraseRequiredReason reason, 309 const sync_pb::EncryptedData& pending_keys) OVERRIDE; 310 virtual void OnPassphraseAccepted() OVERRIDE; 311 virtual void OnEncryptedTypesChanged( 312 syncer::ModelTypeSet encrypted_types, 313 bool encrypt_everything) OVERRIDE; 314 virtual void OnEncryptionComplete() OVERRIDE; 315 virtual void OnMigrationNeededForTypes( 316 syncer::ModelTypeSet types) OVERRIDE; 317 virtual void OnExperimentsChanged( 318 const syncer::Experiments& experiments) OVERRIDE; 319 virtual void OnActionableError( 320 const syncer::SyncProtocolError& error) OVERRIDE; 321 322 // DataTypeManagerObserver implementation. 323 virtual void OnConfigureDone( 324 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE; 325 virtual void OnConfigureRetry() OVERRIDE; 326 virtual void OnConfigureStart() OVERRIDE; 327 328 // DataTypeEncryptionHandler implementation. 329 virtual bool IsPassphraseRequired() const OVERRIDE; 330 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE; 331 332 // Update the last auth error and notify observers of error state. 333 void UpdateAuthErrorState(const GoogleServiceAuthError& error); 334 335 // Called when a user chooses which data types to sync as part of the sync 336 // setup wizard. |sync_everything| represents whether they chose the 337 // "keep everything synced" option; if true, |chosen_types| will be ignored 338 // and all data types will be synced. |sync_everything| means "sync all 339 // current and future data types." 340 virtual void OnUserChoseDatatypes(bool sync_everything, 341 syncer::ModelTypeSet chosen_types); 342 343 // Get various information for displaying in the user interface. 344 std::string QuerySyncStatusSummary(); 345 346 // Initializes a struct of status indicators with data from the backend. 347 // Returns false if the backend was not available for querying; in that case 348 // the struct will be filled with default data. 349 virtual bool QueryDetailedSyncStatus( 350 browser_sync::SyncBackendHost::Status* result); 351 352 virtual const GoogleServiceAuthError& GetAuthError() const; 353 354 // Returns true if initial sync setup is in progress (does not return true 355 // if the user is customizing sync after already completing setup once). 356 // ProfileSyncService uses this to determine if it's OK to start syncing, or 357 // if the user is still setting up the initial sync configuration. 358 virtual bool FirstSetupInProgress() const; 359 360 // Called by the UI to notify the ProfileSyncService that UI is visible so it 361 // will not start syncing. This tells sync whether it's safe to start 362 // downloading data types yet (we don't start syncing until after sync setup 363 // is complete). The UI calls this as soon as any part of the signin wizard is 364 // displayed (even just the login UI). 365 // If |setup_in_progress| is false, this also kicks the sync engine to ensure 366 // that data download starts. 367 virtual void SetSetupInProgress(bool setup_in_progress); 368 369 // Returns true if the SyncBackendHost has told us it's ready to accept 370 // changes. 371 // [REMARK] - it is safe to call this function only from the ui thread. 372 // because the variable is not thread safe and should only be accessed from 373 // single thread. If we want multiple threads to access this(and there is 374 // currently no need to do so) we need to protect this with a lock. 375 // TODO(timsteele): What happens if the bookmark model is loaded, a change 376 // takes place, and the backend isn't initialized yet? 377 virtual bool sync_initialized() const; 378 379 virtual bool HasUnrecoverableError() const; 380 const std::string& unrecoverable_error_message() { 381 return unrecoverable_error_message_; 382 } 383 tracked_objects::Location unrecoverable_error_location() { 384 return unrecoverable_error_location_; 385 } 386 387 // Returns true if OnPassphraseRequired has been called for decryption and 388 // we have an encrypted data type enabled. 389 virtual bool IsPassphraseRequiredForDecryption() const; 390 391 syncer::PassphraseRequiredReason passphrase_required_reason() const { 392 return passphrase_required_reason_; 393 } 394 395 // Returns a user-friendly string form of last synced time (in minutes). 396 virtual string16 GetLastSyncedTimeString() const; 397 398 // Returns a human readable string describing backend initialization state. 399 std::string GetBackendInitializationStateString() const; 400 401 // Returns true if startup is suppressed (i.e. user has stopped syncing via 402 // the google dashboard). 403 virtual bool IsStartSuppressed() const; 404 405 ProfileSyncComponentsFactory* factory() { return factory_.get(); } 406 407 // The profile we are syncing for. 408 Profile* profile() const { return profile_; } 409 410 // Returns a weak pointer to the service's JsController. 411 // Overrideable for testing purposes. 412 virtual base::WeakPtr<syncer::JsController> GetJsController(); 413 414 // Record stats on various events. 415 static void SyncEvent(SyncEventCodes code); 416 417 // Returns whether sync is enabled. Sync can be enabled/disabled both 418 // at compile time (e.g., on a per-OS basis) or at run time (e.g., 419 // command-line switches). 420 // Profile::IsSyncAccessible() is probably a better signal than this function. 421 // This function can be called from any thread, and the implementation doesn't 422 // assume it's running on the UI thread. 423 static bool IsSyncEnabled(); 424 425 // Returns whether sync is managed, i.e. controlled by configuration 426 // management. If so, the user is not allowed to configure sync. 427 virtual bool IsManaged() const; 428 429 // SigninGlobalError::AuthStatusProvider implementation. 430 virtual GoogleServiceAuthError GetAuthStatus() const OVERRIDE; 431 432 // syncer::UnrecoverableErrorHandler implementation. 433 virtual void OnUnrecoverableError( 434 const tracked_objects::Location& from_here, 435 const std::string& message) OVERRIDE; 436 437 // Called when a datatype wishes to disable itself due to having hit an 438 // unrecoverable error. 439 virtual void DisableBrokenDatatype( 440 syncer::ModelType type, 441 const tracked_objects::Location& from_here, 442 std::string message); 443 444 // The functions below (until ActivateDataType()) should only be 445 // called if sync_initialized() is true. 446 447 // TODO(akalin): This is called mostly by ModelAssociators and 448 // tests. Figure out how to pass the handle to the ModelAssociators 449 // directly, figure out how to expose this to tests, and remove this 450 // function. 451 virtual syncer::UserShare* GetUserShare() const; 452 453 // TODO(akalin): These two functions are used only by 454 // ProfileSyncServiceHarness. Figure out a different way to expose 455 // this info to that class, and remove these functions. 456 457 virtual syncer::sessions::SyncSessionSnapshot 458 GetLastSessionSnapshot() const; 459 460 // Returns whether or not the underlying sync engine has made any 461 // local changes to items that have not yet been synced with the 462 // server. 463 bool HasUnsyncedItems() const; 464 465 // Used by ProfileSyncServiceHarness. May return NULL. 466 browser_sync::BackendMigrator* GetBackendMigratorForTest(); 467 468 // TODO(sync): This is only used in tests. Can we remove it? 469 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const; 470 471 // Returns a ListValue indicating the status of all registered types. 472 // 473 // The format is: 474 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ] 475 // where <name> is a type's name, <value> is a string providing details for 476 // the type's status, and <status> is one of "error", "warning" or "ok" 477 // dpending on the type's current status. 478 // 479 // This function is used by sync_ui_util.cc to help populate the about:sync 480 // page. It returns a ListValue rather than a DictionaryValue in part to make 481 // it easier to iterate over its elements when constructing that page. 482 Value* GetTypeStatusMap() const; 483 484 // Overridden by tests. 485 // TODO(zea): Remove these and have the dtc's call directly into the SBH. 486 virtual void ActivateDataType( 487 syncer::ModelType type, syncer::ModelSafeGroup group, 488 browser_sync::ChangeProcessor* change_processor); 489 virtual void DeactivateDataType(syncer::ModelType type); 490 491 // SyncPrefObserver implementation. 492 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE; 493 494 // content::NotificationObserver implementation. 495 virtual void Observe(int type, 496 const content::NotificationSource& source, 497 const content::NotificationDetails& details) OVERRIDE; 498 499 // Changes which data types we're going to be syncing to |preferred_types|. 500 // If it is running, the DataTypeManager will be instructed to reconfigure 501 // the sync backend so that exactly these datatypes are actively synced. See 502 // class comment for more on what it means for a datatype to be Preferred. 503 virtual void ChangePreferredDataTypes( 504 syncer::ModelTypeSet preferred_types); 505 506 // Returns the set of types which are preferred for enabling. This is a 507 // superset of the active types (see GetActiveTypes()). 508 virtual syncer::ModelTypeSet GetPreferredDataTypes() const; 509 510 // Gets the set of all data types that could be allowed (the set that 511 // should be advertised to the user). These will typically only change 512 // via a command-line option. See class comment for more on what it means 513 // for a datatype to be Registered. 514 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const; 515 516 // Checks whether the Cryptographer is ready to encrypt and decrypt updates 517 // for sensitive data types. Caller must be holding a 518 // syncapi::BaseTransaction to ensure thread safety. 519 virtual bool IsCryptographerReady( 520 const syncer::BaseTransaction* trans) const; 521 522 // Returns true if a secondary (explicit) passphrase is being used. It is not 523 // legal to call this method before the backend is initialized. 524 virtual bool IsUsingSecondaryPassphrase() const; 525 526 // Returns the actual passphrase type being used for encryption. 527 virtual syncer::PassphraseType GetPassphraseType() const; 528 529 // Returns the time the current explicit passphrase (if any), was set. 530 // If no secondary passphrase is in use, or no time is available, returns an 531 // unset base::Time. 532 virtual base::Time GetExplicitPassphraseTime() const; 533 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. 540 541 // Asynchronously sets the passphrase to |passphrase| for encryption. |type| 542 // specifies whether the passphrase is a custom passphrase or the GAIA 543 // password being reused as a passphrase. 544 // TODO(atwilson): Change this so external callers can only set an EXPLICIT 545 // passphrase with this API. 546 virtual void SetEncryptionPassphrase(const std::string& passphrase, 547 PassphraseType type); 548 549 // Asynchronously decrypts pending keys using |passphrase|. Returns false 550 // immediately if the passphrase could not be used to decrypt a locally cached 551 // copy of encrypted keys; returns true otherwise. 552 virtual bool SetDecryptionPassphrase(const std::string& passphrase) 553 WARN_UNUSED_RESULT; 554 555 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes() 556 // after calling this to force the encryption to occur. 557 virtual void EnableEncryptEverything(); 558 559 // Returns true if we are currently set to encrypt all the sync data. Note: 560 // this is based on the cryptographer's settings, so if the user has recently 561 // requested encryption to be turned on, this may not be true yet. For that, 562 // encryption_pending() must be checked. 563 virtual bool EncryptEverythingEnabled() const; 564 565 // Returns true if the syncer is waiting for new datatypes to be encrypted. 566 virtual bool encryption_pending() const; 567 568 const GURL& sync_service_url() const { return sync_service_url_; } 569 bool auto_start_enabled() const { return auto_start_enabled_; } 570 SigninManagerBase* signin() const { return signin_; } 571 bool setup_in_progress() const { return setup_in_progress_; } 572 573 // Stops the sync backend and sets the flag for suppressing sync startup. 574 void StopAndSuppress(); 575 576 // Resets the flag for suppressing sync startup and starts the sync backend. 577 virtual void UnsuppressAndStart(); 578 579 // Marks all currently registered types as "acknowledged" so we won't prompt 580 // the user about them any more. 581 void AcknowledgeSyncedTypes(); 582 583 SyncGlobalError* sync_global_error() { return sync_global_error_.get(); } 584 585 // TODO(sync): This is only used in tests. Can we remove it? 586 const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const; 587 588 browser_sync::DataTypeManager::ConfigureStatus configure_status() { 589 return configure_status_; 590 } 591 592 // If true, the ProfileSyncService has detected that a new GAIA signin has 593 // succeeded, and is waiting for initialization to complete. This is used by 594 // the UI to differentiate between a new auth error (encountered as part of 595 // the initialization process) and a pre-existing auth error that just hasn't 596 // been cleared yet. Virtual for testing purposes. 597 virtual bool waiting_for_auth() const; 598 599 // The set of currently enabled sync experiments. 600 const syncer::Experiments& current_experiments() const; 601 602 // OAuth2TokenService::Consumer implementation. 603 virtual void OnGetTokenSuccess( 604 const OAuth2TokenService::Request* request, 605 const std::string& access_token, 606 const base::Time& expiration_time) OVERRIDE; 607 virtual void OnGetTokenFailure( 608 const OAuth2TokenService::Request* request, 609 const GoogleServiceAuthError& error) OVERRIDE; 610 611 // OAuth2TokenService::Observer implementation. 612 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE; 613 virtual void OnRefreshTokenRevoked( 614 const std::string& account_id, 615 const GoogleServiceAuthError& error) OVERRIDE; 616 virtual void OnRefreshTokensLoaded() OVERRIDE; 617 virtual void OnRefreshTokensCleared() OVERRIDE; 618 619 // BrowserContextKeyedService implementation. This must be called exactly 620 // once (before this object is destroyed). 621 virtual void Shutdown() OVERRIDE; 622 623 // Called when a datatype (SyncableService) has a need for sync to start 624 // ASAP, presumably because a local change event has occurred but we're 625 // still in deferred start mode, meaning the SyncableService hasn't been 626 // told to MergeDataAndStartSyncing yet. 627 void OnDataTypeRequestsSyncStartup(syncer::ModelType type); 628 629 protected: 630 // Used by test classes that derive from ProfileSyncService. 631 virtual browser_sync::SyncBackendHost* GetBackendForTest(); 632 633 // Helper to configure the priority data types. 634 void ConfigurePriorityDataTypes(); 635 636 // Helper to install and configure a data type manager. 637 void ConfigureDataTypeManager(); 638 639 // Shuts down the backend sync components. 640 // |option| indicates if syncing is being disabled or not, and whether 641 // to claim ownership of sync thread from backend. 642 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option); 643 644 // Return SyncCredentials from the TokenService. 645 syncer::SyncCredentials GetCredentials(); 646 647 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler(); 648 649 // Test need to override this to create backends that allow setting up 650 // initial conditions, such as populating sync nodes. 651 // 652 // TODO(akalin): Figure out a better way to do this. Ideally, we'd 653 // construct the backend outside this class and pass it in to the 654 // contructor or Initialize(). 655 virtual void CreateBackend(); 656 657 const browser_sync::DataTypeController::TypeMap& data_type_controllers() { 658 return data_type_controllers_; 659 } 660 661 // Helper method for managing encryption UI. 662 bool IsEncryptedDatatypeEnabled() const; 663 664 // Helper for OnUnrecoverableError. 665 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl, 666 // and in SyncBackendHost::Shutdown. 667 void OnUnrecoverableErrorImpl( 668 const tracked_objects::Location& from_here, 669 const std::string& message, 670 bool delete_sync_database); 671 672 // This is a cache of the last authentication response we received from the 673 // sync server. The UI queries this to display appropriate messaging to the 674 // user. 675 GoogleServiceAuthError last_auth_error_; 676 677 // Our asynchronous backend to communicate with sync components living on 678 // other threads. 679 scoped_ptr<browser_sync::SyncBackendHost> backend_; 680 681 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it 682 // was required for encryption, decryption with a cached passphrase, or 683 // because a new passphrase is required? 684 syncer::PassphraseRequiredReason passphrase_required_reason_; 685 686 private: 687 enum UnrecoverableErrorReason { 688 ERROR_REASON_UNSET, 689 ERROR_REASON_SYNCER, 690 ERROR_REASON_BACKEND_INIT_FAILURE, 691 ERROR_REASON_CONFIGURATION_RETRY, 692 ERROR_REASON_CONFIGURATION_FAILURE, 693 ERROR_REASON_ACTIONABLE_ERROR, 694 ERROR_REASON_LIMIT 695 }; 696 friend class ProfileSyncServicePasswordTest; 697 friend class SyncTest; 698 friend class TestProfileSyncService; 699 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState); 700 701 // Detects and attempts to recover from a previous improper datatype 702 // configuration where Keep Everything Synced and the preferred types were 703 // not correctly set. 704 void TrySyncDatatypePrefRecovery(); 705 706 // Starts up sync if it is not suppressed and preconditions are met. 707 // Called from Initialize() and UnsuppressAndStart(). 708 void TryStart(); 709 710 // Puts the backend's sync scheduler into NORMAL mode. 711 // Called when configuration is complete. 712 void StartSyncingWithServer(); 713 714 // Called when we've determined that we don't need a passphrase (either 715 // because OnPassphraseAccepted() was called, or because we've gotten a 716 // OnPassphraseRequired() but no data types are enabled). 717 void ResolvePassphraseRequired(); 718 719 // During initial signin, ProfileSyncService caches the user's signin 720 // passphrase so it can be used to encrypt/decrypt data after sync starts up. 721 // This routine is invoked once the backend has started up to use the 722 // cached passphrase and clear it out when it is done. 723 void ConsumeCachedPassphraseIfPossible(); 724 725 // RequestAccessToken initiates RPC to request downscoped access token from 726 // refresh token. This happens when TokenService loads OAuth2 login token and 727 // when sync server returns AUTH_ERROR which indicates it is time to refresh 728 // token. 729 virtual void RequestAccessToken(); 730 731 // If |delete_sync_data_folder| is true, then this method will delete all 732 // previous "Sync Data" folders. (useful if the folder is partial/corrupt). 733 void InitializeBackend(bool delete_sync_data_folder); 734 735 // Initializes the various settings from the command line. 736 void InitSettings(); 737 738 // Sets the last synced time to the current time. 739 void UpdateLastSyncedTime(); 740 741 void NotifyObservers(); 742 void NotifySyncCycleCompleted(); 743 744 void ClearStaleErrors(); 745 746 void ClearUnrecoverableError(); 747 748 enum StartUpDeferredOption { 749 STARTUP_BACKEND_DEFERRED, 750 STARTUP_IMMEDIATE 751 }; 752 void StartUp(StartUpDeferredOption deferred_option); 753 754 // Starts up the backend sync components. 755 void StartUpSlowBackendComponents(); 756 757 // About-flags experiment names for datatypes that aren't enabled by default 758 // yet. 759 static std::string GetExperimentNameForDataType( 760 syncer::ModelType data_type); 761 762 // Create and register a new datatype controller. 763 void RegisterNewDataType(syncer::ModelType data_type); 764 765 // Reconfigures the data type manager with the latest enabled types. 766 // Note: Does not initialize the backend if it is not already initialized. 767 // This function needs to be called only after sync has been initialized 768 // (i.e.,only for reconfigurations). The reason we don't initialize the 769 // backend is because if we had encountered an unrecoverable error we don't 770 // want to startup once more. 771 virtual void ReconfigureDatatypeManager(); 772 773 // Called when the user changes the sync configuration, to update the UMA 774 // stats. 775 void UpdateSelectedTypesHistogram( 776 bool sync_everything, 777 const syncer::ModelTypeSet chosen_types) const; 778 779 #if defined(OS_CHROMEOS) 780 // Refresh spare sync bootstrap token for re-enabling the sync service. 781 // Called on successful sign-in notifications. 782 void RefreshSpareBootstrapToken(const std::string& passphrase); 783 #endif 784 785 // Internal unrecoverable error handler. Used to track error reason via 786 // Sync.UnrecoverableErrors histogram. 787 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here, 788 const std::string& message, 789 bool delete_sync_database, 790 UnrecoverableErrorReason reason); 791 792 // Returns the username (in form of an email address) that should be used in 793 // the credentials. 794 std::string GetEffectiveUsername(); 795 796 // Factory used to create various dependent objects. 797 scoped_ptr<ProfileSyncComponentsFactory> factory_; 798 799 // The profile whose data we are synchronizing. 800 Profile* profile_; 801 802 // The class that handles getting, setting, and persisting sync 803 // preferences. 804 browser_sync::SyncPrefs sync_prefs_; 805 806 // TODO(ncarter): Put this in a profile, once there is UI for it. 807 // This specifies where to find the sync server. 808 GURL sync_service_url_; 809 810 // The last time we detected a successful transition from SYNCING state. 811 // Our backend notifies us whenever we should take a new snapshot. 812 base::Time last_synced_time_; 813 814 // The time that StartUp() is called. This member is zero if StartUp() has 815 // never been called, and is reset to zero once OnBackendInitialized() is 816 // called. 817 base::Time start_up_time_; 818 819 // Whether we have received a signal from a SyncableService requesting that 820 // sync starts as soon as possible. 821 // TODO(tim): Move this and other TryStart related logic + state to separate 822 // class. Bug 80149. 823 bool data_type_requested_sync_startup_; 824 825 // The time that OnConfigureStart is called. This member is zero if 826 // OnConfigureStart has not yet been called, and is reset to zero once 827 // OnConfigureDone is called. 828 base::Time sync_configure_start_time_; 829 830 // Indicates if this is the first time sync is being configured. This value 831 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized(). 832 bool is_first_time_sync_configure_; 833 834 // List of available data type controllers. 835 browser_sync::DataTypeController::TypeMap data_type_controllers_; 836 837 // Whether the SyncBackendHost has been initialized. 838 bool backend_initialized_; 839 840 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents 841 // ProfileSyncService from starting backend till browser restarted or user 842 // signed out. 843 bool sync_disabled_by_admin_; 844 845 // Set to true if a signin has completed but we're still waiting for the 846 // backend to refresh its credentials. 847 bool is_auth_in_progress_; 848 849 // Encapsulates user signin - used to set/get the user's authenticated 850 // email address. 851 SigninManagerBase* signin_; 852 853 // Information describing an unrecoverable error. 854 UnrecoverableErrorReason unrecoverable_error_reason_; 855 std::string unrecoverable_error_message_; 856 tracked_objects::Location unrecoverable_error_location_; 857 858 // Manages the start and stop of the various data types. 859 scoped_ptr<browser_sync::DataTypeManager> data_type_manager_; 860 861 ObserverList<ProfileSyncServiceBase::Observer> observers_; 862 863 syncer::SyncJsController sync_js_controller_; 864 865 content::NotificationRegistrar registrar_; 866 867 base::WeakPtrFactory<ProfileSyncService> weak_factory_; 868 869 // This allows us to gracefully handle an ABORTED return code from the 870 // DataTypeManager in the event that the server informed us to cease and 871 // desist syncing immediately. 872 bool expect_sync_configuration_aborted_; 873 874 // Sometimes we need to temporarily hold on to a passphrase because we don't 875 // yet have a backend to send it to. This happens during initialization as 876 // we don't StartUp until we have a valid token, which happens after valid 877 // credentials were provided. 878 std::string cached_passphrase_; 879 880 // The current set of encrypted types. Always a superset of 881 // syncer::Cryptographer::SensitiveTypes(). 882 syncer::ModelTypeSet encrypted_types_; 883 884 // Whether we want to encrypt everything. 885 bool encrypt_everything_; 886 887 // Whether we're waiting for an attempt to encryption all sync data to 888 // complete. We track this at this layer in order to allow the user to cancel 889 // if they e.g. don't remember their explicit passphrase. 890 bool encryption_pending_; 891 892 // If true, we want to automatically start sync signin whenever we have 893 // credentials (user doesn't need to go through the startup flow). This is 894 // typically enabled on platforms (like ChromeOS) that have their own 895 // distinct signin flow. 896 const bool auto_start_enabled_; 897 898 scoped_ptr<browser_sync::BackendMigrator> migrator_; 899 900 // This is the last |SyncProtocolError| we received from the server that had 901 // an action set on it. 902 syncer::SyncProtocolError last_actionable_error_; 903 904 // This is used to show sync errors in the wrench menu. 905 scoped_ptr<SyncGlobalError> sync_global_error_; 906 907 // Tracks the set of failed data types (those that encounter an error 908 // or must delay loading for some reason). 909 browser_sync::FailedDataTypesHandler failed_data_types_handler_; 910 911 browser_sync::DataTypeManager::ConfigureStatus configure_status_; 912 913 // If |true|, there is setup UI visible so we should not start downloading 914 // data types. 915 bool setup_in_progress_; 916 917 // The set of currently enabled sync experiments. 918 syncer::Experiments current_experiments_; 919 920 // Sync's internal debug info listener. Used to record datatype configuration 921 // and association information. 922 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_; 923 924 // A thread where all the sync operations happen. 925 // OWNERSHIP Notes: 926 // * Created when backend starts for the first time. 927 // * If sync is disabled, PSS claims ownership from backend. 928 // * If sync is reenabled, PSS passes ownership to new backend. 929 scoped_ptr<base::Thread> sync_thread_; 930 931 // Specifies whenever to use oauth2 access token or ClientLogin token in 932 // communications with sync and xmpp servers. 933 // TODO(pavely): Remove once android is converted to oauth2 tokens. 934 bool use_oauth2_token_; 935 936 // ProfileSyncService needs to remember access token in order to invalidate it 937 // with OAuth2TokenService. 938 std::string access_token_; 939 940 // ProfileSyncService needs to hold reference to access_token_request_ for 941 // the duration of request in order to receive callbacks. 942 scoped_ptr<OAuth2TokenService::Request> access_token_request_; 943 944 // If RequestAccessToken fails with transient error then retry requesting 945 // access token with exponential backoff. 946 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_; 947 net::BackoffEntry request_access_token_backoff_; 948 949 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService); 950 }; 951 952 bool ShouldShowActionOnUI( 953 const syncer::SyncProtocolError& error); 954 955 956 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 957