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