blob: 40d198af19f3e1dc8bdaa150a257b0f9c570da43 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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#include "chrome/browser/sync/profile_sync_service.h"
6
7#include <cstddef>
8#include <map>
9#include <set>
10#include <utility>
11
12#include "base/basictypes.h"
13#include "base/bind.h"
14#include "base/callback.h"
15#include "base/command_line.h"
16#include "base/compiler_specific.h"
17#include "base/logging.h"
18#include "base/memory/ref_counted.h"
Ben Murdoch9ab55632013-07-18 11:57:30 +010019#include "base/message_loop/message_loop.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000020#include "base/metrics/histogram.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010021#include "base/strings/string16.h"
22#include "base/strings/stringprintf.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000023#include "base/threading/thread_restrictions.h"
24#include "build/build_config.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000025#include "chrome/browser/browser_process.h"
Ben Murdoch7dbb3d52013-07-17 14:55:54 +010026#include "chrome/browser/chrome_notification_types.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000027#include "chrome/browser/defaults.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000028#include "chrome/browser/net/chrome_cookie_notification_details.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000029#include "chrome/browser/prefs/pref_service_syncable.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000030#include "chrome/browser/profiles/profile.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010031#include "chrome/browser/signin/about_signin_internals.h"
32#include "chrome/browser/signin/about_signin_internals_factory.h"
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +010033#include "chrome/browser/signin/profile_oauth2_token_service.h"
34#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000035#include "chrome/browser/signin/signin_manager.h"
36#include "chrome/browser/signin/signin_manager_factory.h"
37#include "chrome/browser/signin/token_service.h"
38#include "chrome/browser/signin/token_service_factory.h"
39#include "chrome/browser/sync/backend_migrator.h"
40#include "chrome/browser/sync/glue/change_processor.h"
41#include "chrome/browser/sync/glue/chrome_encryptor.h"
42#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
43#include "chrome/browser/sync/glue/data_type_controller.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000044#include "chrome/browser/sync/glue/device_info.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000045#include "chrome/browser/sync/glue/session_data_type_controller.h"
46#include "chrome/browser/sync/glue/session_model_associator.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000047#include "chrome/browser/sync/glue/synced_device_tracker.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000048#include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
49#include "chrome/browser/sync/profile_sync_components_factory_impl.h"
50#include "chrome/browser/sync/sync_global_error.h"
51#include "chrome/browser/sync/user_selectable_sync_type.h"
52#include "chrome/browser/ui/browser.h"
53#include "chrome/browser/ui/browser_list.h"
54#include "chrome/browser/ui/browser_window.h"
55#include "chrome/browser/ui/global_error/global_error_service.h"
56#include "chrome/browser/ui/global_error/global_error_service_factory.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000057#include "chrome/common/chrome_switches.h"
58#include "chrome/common/chrome_version_info.h"
59#include "chrome/common/pref_names.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000060#include "chrome/common/url_constants.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000061#include "components/user_prefs/pref_registry_syncable.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000062#include "content/public/browser/notification_details.h"
63#include "content/public/browser/notification_service.h"
64#include "content/public/browser/notification_source.h"
65#include "google_apis/gaia/gaia_constants.h"
66#include "grit/generated_resources.h"
67#include "net/cookies/cookie_monster.h"
Ben Murdocheb525c52013-07-10 11:40:50 +010068#include "net/url_request/url_request_context_getter.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000069#include "sync/api/sync_error.h"
70#include "sync/internal_api/public/configure_reason.h"
71#include "sync/internal_api/public/sync_encryption_handler.h"
72#include "sync/internal_api/public/util/experiments.h"
73#include "sync/internal_api/public/util/sync_string_conversions.h"
74#include "sync/js/js_arg_list.h"
75#include "sync/js/js_event_details.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000076#include "sync/util/cryptographer.h"
77#include "ui/base/l10n/l10n_util.h"
Ben Murdochbb1529c2013-08-08 10:24:53 +010078#include "ui/base/l10n/time_format.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000079
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +010080#if defined(ENABLE_MANAGED_USERS)
81#include "chrome/browser/managed_mode/managed_user_service.h"
82#endif
83
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000084#if defined(OS_ANDROID)
85#include "sync/internal_api/public/read_transaction.h"
86#endif
87
Torne (Richard Coles)58218062012-11-14 11:43:16 +000088using browser_sync::ChangeProcessor;
89using browser_sync::DataTypeController;
90using browser_sync::DataTypeManager;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010091using browser_sync::FailedDataTypesHandler;
Torne (Richard Coles)58218062012-11-14 11:43:16 +000092using browser_sync::SyncBackendHost;
93using syncer::ModelType;
94using syncer::ModelTypeSet;
95using syncer::JsBackend;
96using syncer::JsController;
97using syncer::JsEventDetails;
98using syncer::JsEventHandler;
99using syncer::ModelSafeRoutingInfo;
100using syncer::SyncCredentials;
101using syncer::SyncProtocolError;
102using syncer::WeakHandle;
103
104typedef GoogleServiceAuthError AuthError;
105
106const char* ProfileSyncService::kSyncServerUrl =
107 "https://clients4.google.com/chrome-sync";
108
109const char* ProfileSyncService::kDevServerUrl =
110 "https://clients4.google.com/chrome-sync/dev";
111
112static const int kSyncClearDataTimeoutInSeconds = 60; // 1 minute.
113
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000114static const char* kSyncUnrecoverableErrorHistogram =
115 "Sync.UnrecoverableErrors";
116
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100117const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
118 // Number of initial errors (in sequence) to ignore before applying
119 // exponential back-off rules.
120 0,
121
122 // Initial delay for exponential back-off in ms.
123 2000,
124
125 // Factor by which the waiting time will be multiplied.
126 2,
127
128 // Fuzzing percentage. ex: 10% will spread requests randomly
129 // between 90%-100% of the calculated time.
130 0.2, // 20%
131
132 // Maximum amount of time we are willing to delay our request in ms.
133 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
134 // RequestAccessToken on connection state change after backoff
135 1000 * 3600 * 4, // 4 hours.
136
137 // Time to keep an entry from being discarded even when it
138 // has no significant state, -1 to never discard.
139 -1,
140
141 // Don't use initial delay unless the last request was an error.
142 false,
143};
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000144
145bool ShouldShowActionOnUI(
146 const syncer::SyncProtocolError& error) {
147 return (error.action != syncer::UNKNOWN_ACTION &&
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100148 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
149 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000150}
151
152ProfileSyncService::ProfileSyncService(ProfileSyncComponentsFactory* factory,
153 Profile* profile,
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100154 SigninManagerBase* signin_manager,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000155 StartBehavior start_behavior)
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000156 : last_auth_error_(AuthError::AuthErrorNone()),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000157 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
158 factory_(factory),
159 profile_(profile),
160 // |profile| may be NULL in unit tests.
161 sync_prefs_(profile_ ? profile_->GetPrefs() : NULL),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000162 sync_service_url_(kDevServerUrl),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100163 data_type_requested_sync_startup_(false),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000164 is_first_time_sync_configure_(false),
165 backend_initialized_(false),
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100166 sync_disabled_by_admin_(false),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000167 is_auth_in_progress_(false),
168 signin_(signin_manager),
169 unrecoverable_error_reason_(ERROR_REASON_UNSET),
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100170 weak_factory_(this),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000171 expect_sync_configuration_aborted_(false),
172 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
173 encrypt_everything_(false),
174 encryption_pending_(false),
175 auto_start_enabled_(start_behavior == AUTO_START),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000176 configure_status_(DataTypeManager::UNKNOWN),
177 setup_in_progress_(false),
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100178 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000179 // By default, dev, canary, and unbranded Chromium users will go to the
180 // development servers. Development servers have more features than standard
181 // sync servers. Users with officially-branded Chrome stable and beta builds
182 // will go to the standard sync servers.
183 //
184 // GetChannel hits the registry on Windows. See http://crbug.com/70380.
185 base::ThreadRestrictions::ScopedAllowIO allow_io;
186 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
187 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
188 channel == chrome::VersionInfo::CHANNEL_BETA) {
189 sync_service_url_ = GURL(kSyncServerUrl);
190 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000191}
192
193ProfileSyncService::~ProfileSyncService() {
194 sync_prefs_.RemoveSyncPrefObserver(this);
195 // Shutdown() should have been called before destruction.
196 CHECK(!backend_initialized_);
197}
198
199bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
200 // Exit if sync is disabled.
201 if (IsManaged() || sync_prefs_.IsStartSuppressed())
202 return false;
203
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100204 // Sync is logged in if there is a non-empty effective username.
205 return !GetEffectiveUsername().empty();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000206}
207
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100208bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
209 // Function name doesn't reflect which token is checked. Function checks
210 // refresh token when use_oauth2_token_ is true (all platforms except android)
211 // and sync token otherwise (for android).
212 // TODO(pavely): Remove "else" part once use_oauth2_token_ is gone.
213 if (use_oauth2_token_) {
214 ProfileOAuth2TokenService* token_service =
215 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
216 if (!token_service)
217 return false;
218 return token_service->RefreshTokenIsAvailable();
219 } else {
220 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
221 if (!token_service)
222 return false;
223 return token_service->HasTokenForService(GaiaConstants::kSyncService);
224 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000225}
226
227void ProfileSyncService::Initialize() {
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100228 if (profile_)
229 SigninGlobalError::GetForProfile(profile_)->AddProvider(this);
230
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000231 InitSettings();
232
233 // We clear this here (vs Shutdown) because we want to remember that an error
234 // happened on shutdown so we can display details (message, location) about it
235 // in about:sync.
236 ClearStaleErrors();
237
238 sync_prefs_.AddSyncPrefObserver(this);
239
240 // For now, the only thing we can do through policy is to turn sync off.
241 if (IsManaged()) {
242 DisableForUser();
243 return;
244 }
245
246 RegisterAuthNotifications();
247
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100248 if (!HasSyncSetupCompleted() || GetEffectiveUsername().empty()) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000249 // Clean up in case of previous crash / setup abort / signout.
250 DisableForUser();
251 }
252
253 TrySyncDatatypePrefRecovery();
254
255 TryStart();
256}
257
258void ProfileSyncService::TrySyncDatatypePrefRecovery() {
259 DCHECK(!sync_initialized());
260 if (!HasSyncSetupCompleted())
261 return;
262
263 // There was a bug where OnUserChoseDatatypes was not properly called on
264 // configuration (see crbug.com/154940). We detect this by checking whether
265 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
266 // completed, it means sync was not properly configured, so we manually
267 // set kSyncKeepEverythingSynced.
268 PrefService* const pref_service = profile_->GetPrefs();
269 if (!pref_service)
270 return;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100271 if (GetPreferredDataTypes().Size() > 1)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000272 return;
273
274 const PrefService::Preference* keep_everything_synced =
275 pref_service->FindPreference(prefs::kSyncKeepEverythingSynced);
276 // This will be false if the preference was properly set or if it's controlled
277 // by policy.
278 if (!keep_everything_synced->IsDefaultValue())
279 return;
280
281 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
282 // types now, before we configure.
283 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
284 sync_prefs_.SetKeepEverythingSynced(true);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100285 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000286 sync_prefs_.SetPreferredDataTypes(registered_types,
287 registered_types);
288}
289
290void ProfileSyncService::TryStart() {
291 if (!IsSyncEnabledAndLoggedIn())
292 return;
293 TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
294 if (!token_service)
295 return;
296 // Don't start the backend if the token service hasn't finished loading tokens
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000297 // yet. Note if the backend is started before the sync token has been loaded,
298 // GetCredentials() will return bogus credentials. On auto_start platforms
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000299 // (like ChromeOS) we don't start sync until tokens are loaded, because the
300 // user can be "signed in" on those platforms long before the tokens get
301 // loaded, and we don't want to generate spurious auth errors.
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100302 if (!IsOAuthRefreshTokenAvailable() &&
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000303 !(!auto_start_enabled_ && token_service->TokensLoadedFromDB())) {
304 return;
305 }
306
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100307 if (use_oauth2_token_) {
308 // If we got here then tokens are loaded and user logged in and sync is
309 // enabled. If OAuth refresh token is not available then something is wrong.
310 // When PSS requests access token, OAuth2TokenService will return error and
311 // PSS will show error to user asking to reauthenticate.
312 UMA_HISTOGRAM_BOOLEAN("Sync.RefreshTokenAvailable",
313 IsOAuthRefreshTokenAvailable());
314 }
315
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000316 // If sync setup has completed we always start the backend. If the user is in
317 // the process of setting up now, we should start the backend to download
318 // account control state / encryption information). If autostart is enabled,
319 // but we haven't completed sync setup, we try to start sync anyway, since
320 // it's possible we crashed/shutdown after logging in but before the backend
321 // finished initializing the last time.
322 //
323 // However, the only time we actually need to start sync _immediately_ is if
324 // we haven't completed sync setup and the user is in the process of setting
325 // up - either they just signed in (for the first time) on an auto-start
326 // platform or they explicitly kicked off sync setup, and e.g we need to
327 // fetch account details like encryption state to populate UI. Otherwise,
328 // for performance reasons and maximizing parallelism at chrome startup, we
329 // defer the heavy lifting for sync init until things have calmed down.
330 if (HasSyncSetupCompleted()) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100331 if (!data_type_requested_sync_startup_)
332 StartUp(STARTUP_BACKEND_DEFERRED);
333 else if (start_up_time_.is_null())
334 StartUp(STARTUP_IMMEDIATE);
335 else
336 StartUpSlowBackendComponents();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000337 } else if (setup_in_progress_ || auto_start_enabled_) {
338 // We haven't completed sync setup. Start immediately if the user explicitly
339 // kicked this off or we're supposed to automatically start syncing.
340 StartUp(STARTUP_IMMEDIATE);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000341 }
342}
343
344void ProfileSyncService::StartSyncingWithServer() {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100345 if (backend_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000346 backend_->StartSyncingWithServer();
347}
348
349void ProfileSyncService::RegisterAuthNotifications() {
Ben Murdochca12bfa2013-07-23 11:17:05 +0100350 ProfileOAuth2TokenService* token_service =
351 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
352 token_service->AddObserver(this);
353
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100354 registrar_.Add(this,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000355 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
356 content::Source<Profile>(profile_));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000357 registrar_.Add(this,
358 chrome::NOTIFICATION_GOOGLE_SIGNED_OUT,
359 content::Source<Profile>(profile_));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000360}
361
Ben Murdochca12bfa2013-07-23 11:17:05 +0100362void ProfileSyncService::UnregisterAuthNotifications() {
363 ProfileOAuth2TokenService* token_service =
364 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
365 token_service->RemoveObserver(this);
366 registrar_.RemoveAll();
367}
368
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000369void ProfileSyncService::RegisterDataTypeController(
370 DataTypeController* data_type_controller) {
371 DCHECK_EQ(data_type_controllers_.count(data_type_controller->type()), 0U);
372 data_type_controllers_[data_type_controller->type()] =
373 data_type_controller;
374}
375
376browser_sync::SessionModelAssociator*
377 ProfileSyncService::GetSessionModelAssociator() {
378 if (data_type_controllers_.find(syncer::SESSIONS) ==
379 data_type_controllers_.end() ||
380 data_type_controllers_.find(syncer::SESSIONS)->second->state() !=
381 DataTypeController::RUNNING) {
382 return NULL;
383 }
384 return static_cast<browser_sync::SessionDataTypeController*>(
385 data_type_controllers_.find(
386 syncer::SESSIONS)->second.get())->GetModelAssociator();
387}
388
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000389scoped_ptr<browser_sync::DeviceInfo>
390ProfileSyncService::GetLocalDeviceInfo() const {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100391 if (backend_) {
392 browser_sync::SyncedDeviceTracker* device_tracker =
393 backend_->GetSyncedDeviceTracker();
394 if (device_tracker)
395 return device_tracker->ReadLocalDeviceInfo();
396 }
397 return scoped_ptr<browser_sync::DeviceInfo>();
398}
399
400scoped_ptr<browser_sync::DeviceInfo>
401ProfileSyncService::GetDeviceInfo(const std::string& client_id) const {
402 if (backend_) {
403 browser_sync::SyncedDeviceTracker* device_tracker =
404 backend_->GetSyncedDeviceTracker();
405 if (device_tracker)
406 return device_tracker->ReadDeviceInfo(client_id);
407 }
408 return scoped_ptr<browser_sync::DeviceInfo>();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000409}
410
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100411ScopedVector<browser_sync::DeviceInfo>
412 ProfileSyncService::GetAllSignedInDevices() const {
413 ScopedVector<browser_sync::DeviceInfo> devices;
414 if (backend_) {
415 browser_sync::SyncedDeviceTracker* device_tracker =
416 backend_->GetSyncedDeviceTracker();
417 if (device_tracker) {
418 // TODO(lipalani) - Make device tracker return a scoped vector.
419 device_tracker->GetAllSyncedDeviceInfo(&devices);
420 }
421 }
422 return devices.Pass();
423}
424
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000425void ProfileSyncService::GetDataTypeControllerStates(
426 browser_sync::DataTypeController::StateMap* state_map) const {
427 for (browser_sync::DataTypeController::TypeMap::const_iterator iter =
428 data_type_controllers_.begin(); iter != data_type_controllers_.end();
429 ++iter)
430 (*state_map)[iter->first] = iter->second.get()->state();
431}
432
433void ProfileSyncService::InitSettings() {
434 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
435
436 // Override the sync server URL from the command-line, if sync server
437 // command-line argument exists.
438 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
439 std::string value(command_line.GetSwitchValueASCII(
440 switches::kSyncServiceURL));
441 if (!value.empty()) {
442 GURL custom_sync_url(value);
443 if (custom_sync_url.is_valid()) {
444 sync_service_url_ = custom_sync_url;
445 } else {
446 LOG(WARNING) << "The following sync URL specified at the command-line "
447 << "is invalid: " << value;
448 }
449 }
450 }
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100451
452 use_oauth2_token_ = !command_line.HasSwitch(
453 switches::kSyncDisableOAuth2Token);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000454}
455
456SyncCredentials ProfileSyncService::GetCredentials() {
457 SyncCredentials credentials;
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100458 credentials.email = GetEffectiveUsername();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000459 DCHECK(!credentials.email.empty());
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100460 if (use_oauth2_token_) {
461 credentials.sync_token = access_token_;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000462 } else {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100463 TokenService* service = TokenServiceFactory::GetForProfile(profile_);
464 if (service->HasTokenForService(GaiaConstants::kSyncService)) {
465 credentials.sync_token = service->GetTokenForService(
466 GaiaConstants::kSyncService);
467 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000468 }
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100469
470 if (credentials.sync_token.empty())
471 credentials.sync_token = "credentials_lost";
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000472 return credentials;
473}
474
475void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100476 if (!backend_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000477 NOTREACHED();
478 return;
479 }
480
481 SyncCredentials credentials = GetCredentials();
482
483 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
484 profile_->GetRequestContext());
485
486 if (delete_stale_data)
487 ClearStaleErrors();
488
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100489 scoped_ptr<syncer::UnrecoverableErrorHandler>
490 backend_unrecoverable_error_handler(
491 new browser_sync::BackendUnrecoverableErrorHandler(
492 MakeWeakHandle(weak_factory_.GetWeakPtr())));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000493
494 backend_->Initialize(
495 this,
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100496 sync_thread_.Pass(),
497 GetJsEventHandler(),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000498 sync_service_url_,
499 credentials,
500 delete_stale_data,
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100501 scoped_ptr<syncer::SyncManagerFactory>(
502 new syncer::SyncManagerFactory).Pass(),
503 backend_unrecoverable_error_handler.Pass(),
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000504 &browser_sync::ChromeReportUnrecoverableError);
505}
506
507void ProfileSyncService::CreateBackend() {
508 backend_.reset(
509 new SyncBackendHost(profile_->GetDebugName(),
Ben Murdocheb525c52013-07-10 11:40:50 +0100510 profile_, sync_prefs_.AsWeakPtr()));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000511}
512
513bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
514 if (encryption_pending())
515 return true;
516 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
517 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
518 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
519 return !Intersection(preferred_types, encrypted_types).Empty();
520}
521
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000522void ProfileSyncService::OnSyncConfigureRetry() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000523 // Note: in order to handle auth failures that arise before the backend is
524 // initialized (e.g. from invalidation notifier, or downloading new control
525 // types), we have to gracefully handle configuration retries at all times.
526 // At this point an auth error badge should be shown, which once resolved
527 // will trigger a new sync cycle.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000528 NotifyObservers();
529}
530
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000531void ProfileSyncService::StartUp(StartUpDeferredOption deferred_option) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000532 // Don't start up multiple times.
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100533 if (backend_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000534 DVLOG(1) << "Skipping bringing up backend host.";
535 return;
536 }
537
538 DCHECK(IsSyncEnabledAndLoggedIn());
539
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100540 if (use_oauth2_token_ && access_token_.empty()) {
541 RequestAccessToken();
542 return;
543 }
544
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100545 if (start_up_time_.is_null()) {
546 start_up_time_ = base::Time::Now();
547 last_synced_time_ = sync_prefs_.GetLastSyncedTime();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000548
549#if defined(OS_CHROMEOS)
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100550 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
551 if (bootstrap_token.empty()) {
552 sync_prefs_.SetEncryptionBootstrapToken(
553 sync_prefs_.GetSpareBootstrapToken());
554 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000555#endif
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000556
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100557 if (!sync_global_error_) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000558#if !defined(OS_ANDROID)
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100559 sync_global_error_.reset(new SyncGlobalError(this, signin()));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000560#endif
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100561 GlobalErrorServiceFactory::GetForProfile(profile_)->AddGlobalError(
562 sync_global_error_.get());
563 AddObserver(sync_global_error_.get());
564 }
565 } else {
566 // We don't care to prevent multiple calls to StartUp in deferred mode
567 // because it's fast and has no side effects.
568 DCHECK_EQ(STARTUP_BACKEND_DEFERRED, deferred_option);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000569 }
570
571 if (deferred_option == STARTUP_BACKEND_DEFERRED &&
572 CommandLine::ForCurrentProcess()->
573 HasSwitch(switches::kSyncEnableDeferredStartup)) {
574 return;
575 }
576
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100577 StartUpSlowBackendComponents();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000578}
579
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100580void ProfileSyncService::OnDataTypeRequestsSyncStartup(
581 syncer::ModelType type) {
582 DCHECK(syncer::UserTypes().Has(type));
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000583 if (backend_.get()) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100584 DVLOG(1) << "A data type requested sync startup, but it looks like "
585 "something else beat it to the punch.";
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000586 return;
587 }
588
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100589 if (!GetActiveDataTypes().Has(type)) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100590 // We can get here as datatype SyncableServices are typically wired up
591 // to the native datatype even if sync isn't enabled.
592 DVLOG(1) << "Dropping sync startup request because type "
593 << syncer::ModelTypeToString(type) << "not enabled.";
594 return;
595 }
596
597 if (CommandLine::ForCurrentProcess()->HasSwitch(
598 switches::kSyncEnableDeferredStartup)) {
599 DVLOG(2) << "Data type requesting sync startup: "
600 << syncer::ModelTypeToString(type);
601 // Measure the time spent waiting for init and the type that triggered it.
602 // We could measure the time spent deferred on a per-datatype basis, but
603 // for now this is probably sufficient.
604 if (!start_up_time_.is_null()) {
605 // TODO(tim): Cache |type| and move this tracking to StartUp. I'd like
606 // to pull all the complicated init logic and state out of
607 // ProfileSyncService and have only a StartUp method, though. One step
608 // at a time. Bug 80149.
609 base::TimeDelta time_deferred = base::Time::Now() - start_up_time_;
610 UMA_HISTOGRAM_TIMES("Sync.Startup.TimeDeferred", time_deferred);
611 UMA_HISTOGRAM_ENUMERATION("Sync.Startup.TypeTriggeringInit",
612 ModelTypeToHistogramInt(type),
613 syncer::MODEL_TYPE_COUNT);
614 }
615 data_type_requested_sync_startup_ = true;
616 TryStart();
617 }
618 DVLOG(2) << "Ignoring data type request for sync startup: "
619 << syncer::ModelTypeToString(type);
620}
621
622void ProfileSyncService::StartUpSlowBackendComponents() {
623 // Don't start up multiple times.
624 if (backend_) {
625 DVLOG(1) << "Skipping bringing up backend host.";
626 return;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000627 }
628
629 DCHECK(IsSyncEnabledAndLoggedIn());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000630 CreateBackend();
631
632 // Initialize the backend. Every time we start up a new SyncBackendHost,
633 // we'll want to start from a fresh SyncDB, so delete any old one that might
634 // be there.
635 InitializeBackend(!HasSyncSetupCompleted());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000636}
637
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100638void ProfileSyncService::OnGetTokenSuccess(
639 const OAuth2TokenService::Request* request,
640 const std::string& access_token,
641 const base::Time& expiration_time) {
642 DCHECK_EQ(access_token_request_, request);
643 access_token_request_.reset();
644 // Reset backoff time after successful response.
645 request_access_token_backoff_.Reset();
646 access_token_ = access_token;
647 if (backend_)
648 backend_->UpdateCredentials(GetCredentials());
649 else
650 TryStart();
651}
652
653void ProfileSyncService::OnGetTokenFailure(
654 const OAuth2TokenService::Request* request,
655 const GoogleServiceAuthError& error) {
656 DCHECK_EQ(access_token_request_, request);
657 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
658 access_token_request_.reset();
659 switch (error.state()) {
660 case GoogleServiceAuthError::CONNECTION_FAILED:
661 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
662 // Transient error. Retry after some time.
663 request_access_token_backoff_.InformOfRequest(false);
664 request_access_token_retry_timer_.Start(
665 FROM_HERE,
666 request_access_token_backoff_.GetTimeUntilRelease(),
667 base::Bind(&ProfileSyncService::RequestAccessToken,
668 weak_factory_.GetWeakPtr()));
669 break;
670 }
671 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
672 // Report time since token was issued for invalid credentials error.
673 // TODO(pavely): crbug.com/246817 Collect UMA histogram for auth token
674 // rejections from invalidation service.
675 base::Time auth_token_time =
676 AboutSigninInternalsFactory::GetForProfile(profile_)->
677 GetTokenTime(GaiaConstants::kGaiaOAuth2LoginRefreshToken);
678 if (!auth_token_time.is_null()) {
679 base::TimeDelta age = base::Time::Now() - auth_token_time;
680 if (age < base::TimeDelta::FromHours(1)) {
681 UMA_HISTOGRAM_CUSTOM_TIMES("Sync.AuthServerRejectedTokenAgeShort",
682 age,
683 base::TimeDelta::FromSeconds(1),
684 base::TimeDelta::FromHours(1),
685 50);
686 }
687 UMA_HISTOGRAM_COUNTS("Sync.AuthServerRejectedTokenAgeLong",
688 age.InDays());
689 }
690 // Fallthrough.
691 }
692 default: {
693 // Show error to user.
694 UpdateAuthErrorState(error);
695 }
696 }
697}
698
Ben Murdochca12bfa2013-07-23 11:17:05 +0100699void ProfileSyncService::OnRefreshTokenAvailable(
700 const std::string& account_id) {
701 OnRefreshTokensLoaded();
702}
703
704void ProfileSyncService::OnRefreshTokenRevoked(
705 const std::string& account_id,
706 const GoogleServiceAuthError& error) {
707 if (!IsOAuthRefreshTokenAvailable()) {
708 // The additional check around IsOAuthRefreshTokenAvailable() above
709 // prevents us sounding the alarm if we actually have a valid token but
710 // a refresh attempt by TokenService failed for any variety of reasons
711 // (e.g. flaky network). It's possible the token we do have is also
712 // invalid, but in that case we should already have (or can expect) an
713 // auth error sent from the sync backend.
714 UpdateAuthErrorState(error);
715 }
716}
717
718void ProfileSyncService::OnRefreshTokensLoaded() {
719 // This notification gets fired when TokenService loads the tokens
720 // from storage.
721 // Initialize the backend if sync is enabled. If the sync token was
722 // not loaded, GetCredentials() will generate invalid credentials to
723 // cause the backend to generate an auth error (crbug.com/121755).
724 if (backend_) {
725 RequestAccessToken();
726 } else {
727 TryStart();
728 }
729}
730
731void ProfileSyncService::OnRefreshTokensCleared() {
732 access_token_.clear();
733}
734
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000735void ProfileSyncService::Shutdown() {
Ben Murdochca12bfa2013-07-23 11:17:05 +0100736 UnregisterAuthNotifications();
737
Ben Murdoch7dbb3d52013-07-17 14:55:54 +0100738 if (profile_)
739 SigninGlobalError::GetForProfile(profile_)->RemoveProvider(this);
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000740
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100741 ShutdownImpl(browser_sync::SyncBackendHost::STOP);
742
743 if (sync_thread_)
744 sync_thread_->Stop();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000745}
746
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100747void ProfileSyncService::ShutdownImpl(
748 browser_sync::SyncBackendHost::ShutdownOption option) {
749 if (!backend_)
750 return;
751
752 // First, we spin down the backend to stop change processing as soon as
753 // possible.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000754 base::Time shutdown_start_time = base::Time::Now();
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100755 backend_->StopSyncingForShutdown();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000756
757 // Stop all data type controllers, if needed. Note that until Stop
758 // completes, it is possible in theory to have a ChangeProcessor apply a
759 // change from a native model. In that case, it will get applied to the sync
760 // database (which doesn't get destroyed until we destroy the backend below)
761 // as an unsynced change. That will be persisted, and committed on restart.
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100762 if (data_type_manager_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000763 if (data_type_manager_->state() != DataTypeManager::STOPPED) {
764 // When aborting as part of shutdown, we should expect an aborted sync
765 // configure result, else we'll dcheck when we try to read the sync error.
766 expect_sync_configuration_aborted_ = true;
767 data_type_manager_->Stop();
768 }
769 data_type_manager_.reset();
770 }
771
772 // Shutdown the migrator before the backend to ensure it doesn't pull a null
773 // snapshot.
774 migrator_.reset();
775 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
776
777 // Move aside the backend so nobody else tries to use it while we are
778 // shutting it down.
779 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100780 if (doomed_backend) {
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100781 sync_thread_ = doomed_backend->Shutdown(option);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000782 doomed_backend.reset();
783 }
784 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
785 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
786
787 weak_factory_.InvalidateWeakPtrs();
788
789 // Clear various flags.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100790 start_up_time_ = base::Time();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000791 expect_sync_configuration_aborted_ = false;
792 is_auth_in_progress_ = false;
793 backend_initialized_ = false;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000794 cached_passphrase_.clear();
795 encryption_pending_ = false;
796 encrypt_everything_ = false;
797 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
798 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +0100799 request_access_token_retry_timer_.Stop();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000800 // Revert to "no auth error".
801 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
802 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000803
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100804 if (sync_global_error_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000805 GlobalErrorServiceFactory::GetForProfile(profile_)->RemoveGlobalError(
806 sync_global_error_.get());
807 RemoveObserver(sync_global_error_.get());
808 sync_global_error_.reset(NULL);
809 }
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100810
811 NotifyObservers();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000812}
813
814void ProfileSyncService::DisableForUser() {
815 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
816 // PSS clients don't think we're set up while we're shutting down.
817 sync_prefs_.ClearPreferences();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000818 ClearUnrecoverableError();
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100819 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000820}
821
822bool ProfileSyncService::HasSyncSetupCompleted() const {
823 return sync_prefs_.HasSyncSetupCompleted();
824}
825
826void ProfileSyncService::SetSyncSetupCompleted() {
827 sync_prefs_.SetSyncSetupCompleted();
828}
829
830void ProfileSyncService::UpdateLastSyncedTime() {
831 last_synced_time_ = base::Time::Now();
832 sync_prefs_.SetLastSyncedTime(last_synced_time_);
833}
834
835void ProfileSyncService::NotifyObservers() {
Ben Murdochca12bfa2013-07-23 11:17:05 +0100836 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
837 OnStateChanged());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000838 // TODO(akalin): Make an Observer subclass that listens and does the
839 // event routing.
Ben Murdocheb525c52013-07-10 11:40:50 +0100840 sync_js_controller_.HandleJsEvent("onServiceStateChanged", JsEventDetails());
841}
842
843void ProfileSyncService::NotifySyncCycleCompleted() {
Ben Murdochca12bfa2013-07-23 11:17:05 +0100844 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
845 OnSyncCycleCompleted());
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000846 sync_js_controller_.HandleJsEvent(
847 "onServiceStateChanged", JsEventDetails());
848}
849
850void ProfileSyncService::ClearStaleErrors() {
851 ClearUnrecoverableError();
852 last_actionable_error_ = SyncProtocolError();
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +0100853 // Clear the data type errors as well.
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100854 failed_data_types_handler_.Reset();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000855}
856
857void ProfileSyncService::ClearUnrecoverableError() {
858 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
859 unrecoverable_error_message_.clear();
860 unrecoverable_error_location_ = tracked_objects::Location();
861}
862
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000863void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) {
864 if (data_type_controllers_.count(data_type) > 0)
865 return;
866 NOTREACHED();
867}
868
869// An invariant has been violated. Transition to an error state where we try
870// to do as little work as possible, to avoid further corruption or crashes.
871void ProfileSyncService::OnUnrecoverableError(
872 const tracked_objects::Location& from_here,
873 const std::string& message) {
874 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
875 // interface are assumed to originate within the syncer.
876 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
877 OnUnrecoverableErrorImpl(from_here, message, true);
878}
879
880void ProfileSyncService::OnUnrecoverableErrorImpl(
881 const tracked_objects::Location& from_here,
882 const std::string& message,
883 bool delete_sync_database) {
884 DCHECK(HasUnrecoverableError());
885 unrecoverable_error_message_ = message;
886 unrecoverable_error_location_ = from_here;
887
888 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
889 unrecoverable_error_reason_,
890 ERROR_REASON_LIMIT);
891 NotifyObservers();
892 std::string location;
893 from_here.Write(true, true, &location);
894 LOG(ERROR)
895 << "Unrecoverable error detected at " << location
896 << " -- ProfileSyncService unusable: " << message;
897
898 // Shut all data types down.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100899 base::MessageLoop::current()->PostTask(FROM_HERE,
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +0100900 base::Bind(&ProfileSyncService::ShutdownImpl,
901 weak_factory_.GetWeakPtr(),
902 delete_sync_database ?
903 browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD :
904 browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD));
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000905}
906
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100907// TODO(zea): Move this logic into the DataTypeController/DataTypeManager.
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000908void ProfileSyncService::DisableBrokenDatatype(
909 syncer::ModelType type,
910 const tracked_objects::Location& from_here,
911 std::string message) {
912 // First deactivate the type so that no further server changes are
913 // passed onto the change processor.
914 DeactivateDataType(type);
915
Ben Murdocheb525c52013-07-10 11:40:50 +0100916 syncer::SyncError error(from_here,
917 syncer::SyncError::DATATYPE_ERROR,
918 message,
919 type);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000920
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +0100921 std::map<syncer::ModelType, syncer::SyncError> errors;
922 errors[type] = error;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000923
924 // Update this before posting a task. So if a configure happens before
925 // the task that we are going to post, this type would still be disabled.
Ben Murdocheb525c52013-07-10 11:40:50 +0100926 failed_data_types_handler_.UpdateFailedDataTypes(errors);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000927
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +0100928 base::MessageLoop::current()->PostTask(FROM_HERE,
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000929 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager,
930 weak_factory_.GetWeakPtr()));
931}
932
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000933void ProfileSyncService::OnBackendInitialized(
934 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
935 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
936 debug_info_listener,
937 bool success) {
938 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
939
940 if (is_first_time_sync_configure_) {
941 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
942 } else {
943 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
944 }
945
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000946 DCHECK(!start_up_time_.is_null());
947 base::Time on_backend_initialized_time = base::Time::Now();
948 base::TimeDelta delta = on_backend_initialized_time - start_up_time_;
949 if (is_first_time_sync_configure_) {
950 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
951 } else {
952 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000953 }
954
955 if (!success) {
956 // Something went unexpectedly wrong. Play it safe: stop syncing at once
957 // and surface error UI to alert the user sync has stopped.
958 // Keep the directory around for now so that on restart we will retry
959 // again and potentially succeed in presence of transient file IO failures
960 // or permissions issues, etc.
961 //
962 // TODO(rlarocque): Consider making this UnrecoverableError less special.
963 // Unlike every other UnrecoverableError, it does not delete our sync data.
964 // This exception made sense at the time it was implemented, but our new
965 // directory corruption recovery mechanism makes it obsolete. By the time
966 // we get here, we will have already tried and failed to delete the
967 // directory. It would be no big deal if we tried to delete it again.
968 OnInternalUnrecoverableError(FROM_HERE,
969 "BackendInitialize failure",
970 false,
971 ERROR_REASON_BACKEND_INIT_FAILURE);
972 return;
973 }
974
975 backend_initialized_ = true;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000976
977 sync_js_controller_.AttachJsBackend(js_backend);
978 debug_info_listener_ = debug_info_listener;
979
980 // If we have a cached passphrase use it to decrypt/encrypt data now that the
981 // backend is initialized. We want to call this before notifying observers in
982 // case this operation affects the "passphrase required" status.
983 ConsumeCachedPassphraseIfPossible();
984
985 // The very first time the backend initializes is effectively the first time
986 // we can say we successfully "synced". last_synced_time_ will only be null
987 // in this case, because the pref wasn't restored on StartUp.
988 if (last_synced_time_.is_null()) {
989 UpdateLastSyncedTime();
990 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000991
992 if (auto_start_enabled_ && !FirstSetupInProgress()) {
993 // Backend is initialized but we're not in sync setup, so this must be an
994 // autostart - mark our sync setup as completed and we'll start syncing
995 // below.
996 SetSyncSetupCompleted();
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000997 }
998
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +0100999 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1000 // data type configuration because observer may flag setup as complete and
1001 // trigger data type configuration.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001002 if (HasSyncSetupCompleted()) {
1003 ConfigureDataTypeManager();
1004 } else {
1005 DCHECK(FirstSetupInProgress());
1006 }
Torne (Richard Coles)a93a17c2013-05-15 11:34:50 +01001007
1008 NotifyObservers();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001009}
1010
1011void ProfileSyncService::OnSyncCycleCompleted() {
1012 UpdateLastSyncedTime();
1013 if (GetSessionModelAssociator()) {
1014 // Trigger garbage collection of old sessions now that we've downloaded
1015 // any new session data. TODO(zea): Have this be a notification the session
1016 // model associator listens too. Also consider somehow plumbing the current
1017 // server time as last reported by CheckServerReachable, so we don't have to
1018 // rely on the local clock, which may be off significantly.
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001019 base::MessageLoop::current()->PostTask(FROM_HERE,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001020 base::Bind(&browser_sync::SessionModelAssociator::DeleteStaleSessions,
1021 GetSessionModelAssociator()->AsWeakPtr()));
1022 }
1023 DVLOG(2) << "Notifying observers sync cycle completed";
Ben Murdocheb525c52013-07-10 11:40:50 +01001024 NotifySyncCycleCompleted();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001025}
1026
1027void ProfileSyncService::OnExperimentsChanged(
1028 const syncer::Experiments& experiments) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001029 if (current_experiments_.Matches(experiments))
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001030 return;
1031
1032 // If this is a first time sync for a client, this will be called before
1033 // OnBackendInitialized() to ensure the new datatypes are available at sync
1034 // setup. As a result, the migrator won't exist yet. This is fine because for
1035 // first time sync cases we're only concerned with making the datatype
1036 // available.
1037 if (migrator_.get() &&
1038 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1039 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1040 return;
1041 }
1042
1043 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1044 syncer::ModelTypeSet to_add;
1045 const syncer::ModelTypeSet to_register =
1046 Difference(to_add, registered_types);
1047 DVLOG(2) << "OnExperimentsChanged called with types: "
1048 << syncer::ModelTypeSetToString(to_add);
1049 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register);
1050
1051 for (syncer::ModelTypeSet::Iterator it = to_register.First();
1052 it.Good(); it.Inc()) {
1053 // Received notice to enable experimental type. Check if the type is
1054 // registered, and if not register a new datatype controller.
1055 RegisterNewDataType(it.Get());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001056 }
1057
1058 // Check if the user has "Keep Everything Synced" enabled. If so, we want
1059 // to turn on all experimental types if they're not already on. Otherwise we
1060 // leave them off.
1061 // Note: if any types are already registered, we don't turn them on. This
1062 // covers the case where we're already in the process of reconfiguring
1063 // to turn an experimental type on.
1064 if (sync_prefs_.HasKeepEverythingSynced()) {
1065 // Mark all data types as preferred.
1066 sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
1067
1068 // Only automatically turn on types if we have already finished set up.
1069 // Otherwise, just leave the experimental types on by default.
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001070 if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001071 DVLOG(1) << "Dynamically enabling new datatypes: "
1072 << syncer::ModelTypeSetToString(to_register);
1073 OnMigrationNeededForTypes(to_register);
1074 }
1075 }
1076
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001077 current_experiments_ = experiments;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001078}
1079
1080void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1081 is_auth_in_progress_ = false;
1082 last_auth_error_ = error;
1083
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001084 // Fan the notification out to interested UI-thread components. Notify the
1085 // SigninGlobalError first so it reflects the latest auth state before we
1086 // notify observers.
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001087 if (profile_)
1088 SigninGlobalError::GetForProfile(profile_)->AuthStatusChanged();
1089
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001090 NotifyObservers();
1091}
1092
1093namespace {
1094
1095AuthError ConnectionStatusToAuthError(
1096 syncer::ConnectionStatus status) {
1097 switch (status) {
1098 case syncer::CONNECTION_OK:
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001099 return AuthError::AuthErrorNone();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001100 break;
1101 case syncer::CONNECTION_AUTH_ERROR:
1102 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1103 break;
1104 case syncer::CONNECTION_SERVER_ERROR:
1105 return AuthError(AuthError::CONNECTION_FAILED);
1106 break;
1107 default:
1108 NOTREACHED();
1109 return AuthError(AuthError::CONNECTION_FAILED);
1110 }
1111}
1112
1113} // namespace
1114
1115void ProfileSyncService::OnConnectionStatusChange(
1116 syncer::ConnectionStatus status) {
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001117 if (use_oauth2_token_ && status == syncer::CONNECTION_AUTH_ERROR) {
Ben Murdocheb525c52013-07-10 11:40:50 +01001118 // Sync server returned error indicating that access token is invalid. It
1119 // could be either expired or access is revoked. Let's request another
1120 // access token and if access is revoked then request for token will fail
1121 // with corresponding error.
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001122 RequestAccessToken();
1123 } else {
1124 const GoogleServiceAuthError auth_error =
1125 ConnectionStatusToAuthError(status);
1126 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1127 UpdateAuthErrorState(auth_error);
1128 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001129}
1130
1131void ProfileSyncService::OnStopSyncingPermanently() {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001132 sync_prefs_.SetStartSuppressed(true);
1133 DisableForUser();
1134}
1135
1136void ProfileSyncService::OnPassphraseRequired(
1137 syncer::PassphraseRequiredReason reason,
1138 const sync_pb::EncryptedData& pending_keys) {
1139 DCHECK(backend_.get());
1140 DCHECK(backend_->IsNigoriEnabled());
1141
1142 // TODO(lipalani) : add this check to other locations as well.
1143 if (HasUnrecoverableError()) {
1144 // When unrecoverable error is detected we post a task to shutdown the
1145 // backend. The task might not have executed yet.
1146 return;
1147 }
1148
1149 DVLOG(1) << "Passphrase required with reason: "
1150 << syncer::PassphraseRequiredReasonToString(reason);
1151 passphrase_required_reason_ = reason;
1152
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001153 const syncer::ModelTypeSet types = GetPreferredDataTypes();
1154 if (data_type_manager_) {
1155 // Reconfigure without the encrypted types (excluded implicitly via the
1156 // failed datatypes handler).
1157 data_type_manager_->Configure(types,
1158 syncer::CONFIGURE_REASON_CRYPTO);
1159 }
1160
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001161 // Notify observers that the passphrase status may have changed.
1162 NotifyObservers();
1163}
1164
1165void ProfileSyncService::OnPassphraseAccepted() {
1166 DVLOG(1) << "Received OnPassphraseAccepted.";
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001167
1168 // If the pending keys were resolved via keystore, it's possible we never
1169 // consumed our cached passphrase. Clear it now.
1170 if (!cached_passphrase_.empty())
1171 cached_passphrase_.clear();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001172
1173 // Reset passphrase_required_reason_ since we know we no longer require the
1174 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1175 // because that can be called by OnPassphraseRequired() if no encrypted data
1176 // types are enabled, and we don't want to clobber the true passphrase error.
1177 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1178
1179 // Make sure the data types that depend on the passphrase are started at
1180 // this time.
1181 const syncer::ModelTypeSet types = GetPreferredDataTypes();
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001182 if (data_type_manager_) {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001183 // Re-enable any encrypted types if necessary.
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001184 data_type_manager_->Configure(types,
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001185 syncer::CONFIGURE_REASON_CRYPTO);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001186 }
1187
1188 NotifyObservers();
1189}
1190
1191void ProfileSyncService::OnEncryptedTypesChanged(
1192 syncer::ModelTypeSet encrypted_types,
1193 bool encrypt_everything) {
1194 encrypted_types_ = encrypted_types;
1195 encrypt_everything_ = encrypt_everything;
1196 DVLOG(1) << "Encrypted types changed to "
1197 << syncer::ModelTypeSetToString(encrypted_types_)
1198 << " (encrypt everything is set to "
1199 << (encrypt_everything_ ? "true" : "false") << ")";
1200 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001201
1202 // If sessions are encrypted, full history sync is not possible, and
1203 // delete directives are unnecessary.
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001204 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES) &&
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001205 encrypted_types_.Has(syncer::SESSIONS)) {
1206 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES,
1207 FROM_HERE,
1208 "Delete directives not supported with encryption.");
1209 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001210}
1211
1212void ProfileSyncService::OnEncryptionComplete() {
1213 DVLOG(1) << "Encryption complete";
1214 if (encryption_pending_ && encrypt_everything_) {
1215 encryption_pending_ = false;
1216 // This is to nudge the integration tests when encryption is
1217 // finished.
1218 NotifyObservers();
1219 }
1220}
1221
1222void ProfileSyncService::OnMigrationNeededForTypes(
1223 syncer::ModelTypeSet types) {
1224 DCHECK(backend_initialized_);
1225 DCHECK(data_type_manager_.get());
1226
1227 // Migrator must be valid, because we don't sync until it is created and this
1228 // callback originates from a sync cycle.
1229 migrator_->MigrateTypes(types);
1230}
1231
1232void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1233 last_actionable_error_ = error;
1234 DCHECK_NE(last_actionable_error_.action,
1235 syncer::UNKNOWN_ACTION);
1236 switch (error.action) {
1237 case syncer::UPGRADE_CLIENT:
1238 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1239 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1240 case syncer::STOP_AND_RESTART_SYNC:
1241 // TODO(lipalani) : if setup in progress we want to display these
1242 // actions in the popup. The current experience might not be optimal for
1243 // the user. We just dismiss the dialog.
1244 if (setup_in_progress_) {
1245 OnStopSyncingPermanently();
1246 expect_sync_configuration_aborted_ = true;
1247 }
1248 // Trigger an unrecoverable error to stop syncing.
1249 OnInternalUnrecoverableError(FROM_HERE,
1250 last_actionable_error_.error_description,
1251 true,
1252 ERROR_REASON_ACTIONABLE_ERROR);
1253 break;
1254 case syncer::DISABLE_SYNC_ON_CLIENT:
1255 OnStopSyncingPermanently();
Ben Murdocheb525c52013-07-10 11:40:50 +01001256#if !defined(OS_CHROMEOS)
1257 // On desktop Chrome, sign out the user after a dashboard clear.
1258 // TODO(rsimha): Revisit this for M30. See http://crbug.com/252049.
1259 if (!auto_start_enabled_) // Skip sign out on ChromeOS/Android.
1260 SigninManagerFactory::GetForProfile(profile_)->SignOut();
1261#endif
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001262 break;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001263 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1264 // Sync disabled by domain admin. we should stop syncing until next
1265 // restart.
1266 sync_disabled_by_admin_ = true;
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01001267 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001268 break;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001269 default:
1270 NOTREACHED();
1271 }
1272 NotifyObservers();
1273}
1274
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001275void ProfileSyncService::OnConfigureDone(
1276 const browser_sync::DataTypeManager::ConfigureResult& result) {
1277 // We should have cleared our cached passphrase before we get here (in
1278 // OnBackendInitialized()).
1279 DCHECK(cached_passphrase_.empty());
1280
1281 if (!sync_configure_start_time_.is_null()) {
1282 if (result.status == DataTypeManager::OK ||
1283 result.status == DataTypeManager::PARTIAL_SUCCESS) {
1284 base::Time sync_configure_stop_time = base::Time::Now();
1285 base::TimeDelta delta = sync_configure_stop_time -
1286 sync_configure_start_time_;
1287 if (is_first_time_sync_configure_) {
1288 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1289 } else {
1290 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1291 delta);
1292 }
1293 }
1294 sync_configure_start_time_ = base::Time();
1295 }
1296
1297 // Notify listeners that configuration is done.
1298 content::NotificationService::current()->Notify(
1299 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1300 content::Source<ProfileSyncService>(this),
1301 content::NotificationService::NoDetails());
1302
1303 configure_status_ = result.status;
1304 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1305 // The possible status values:
1306 // ABORT - Configuration was aborted. This is not an error, if
1307 // initiated by user.
1308 // OK - Everything succeeded.
1309 // PARTIAL_SUCCESS - Some datatypes failed to start.
1310 // Everything else is an UnrecoverableError. So treat it as such.
1311
1312 // First handle the abort case.
1313 if (configure_status_ == DataTypeManager::ABORTED &&
1314 expect_sync_configuration_aborted_) {
1315 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1316 expect_sync_configuration_aborted_ = false;
1317 return;
1318 }
1319
1320 // Handle unrecoverable error.
1321 if (configure_status_ != DataTypeManager::OK &&
1322 configure_status_ != DataTypeManager::PARTIAL_SUCCESS) {
1323 // Something catastrophic had happened. We should only have one
1324 // error representing it.
1325 DCHECK_EQ(result.failed_data_types.size(),
1326 static_cast<unsigned int>(1));
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001327 syncer::SyncError error = result.failed_data_types.begin()->second;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001328 DCHECK(error.IsSet());
1329 std::string message =
1330 "Sync configuration failed with status " +
1331 DataTypeManager::ConfigureStatusToString(configure_status_) +
Ben Murdocheb525c52013-07-10 11:40:50 +01001332 " during " + syncer::ModelTypeToString(error.model_type()) +
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001333 ": " + error.message();
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001334 LOG(ERROR) << "ProfileSyncService error: " << message;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001335 OnInternalUnrecoverableError(error.location(),
1336 message,
1337 true,
1338 ERROR_REASON_CONFIGURATION_FAILURE);
1339 return;
1340 }
1341
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001342 // We should never get in a state where we have no encrypted datatypes
1343 // enabled, and yet we still think we require a passphrase for decryption.
1344 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1345 !IsEncryptedDatatypeEnabled()));
1346
1347 // This must be done before we start syncing with the server to avoid
1348 // sending unencrypted data up on a first time sync.
1349 if (encryption_pending_)
1350 backend_->EnableEncryptEverything();
1351 NotifyObservers();
1352
1353 if (migrator_.get() &&
1354 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1355 // Migration in progress. Let the migrator know we just finished
1356 // configuring something. It will be up to the migrator to call
1357 // StartSyncingWithServer() if migration is now finished.
1358 migrator_->OnConfigureDone(result);
1359 } else {
1360 StartSyncingWithServer();
1361 }
1362}
1363
1364void ProfileSyncService::OnConfigureRetry() {
1365 // We should have cleared our cached passphrase before we get here (in
1366 // OnBackendInitialized()).
1367 DCHECK(cached_passphrase_.empty());
1368
1369 OnSyncConfigureRetry();
1370}
1371
1372void ProfileSyncService::OnConfigureStart() {
1373 sync_configure_start_time_ = base::Time::Now();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001374 NotifyObservers();
1375}
1376
1377std::string ProfileSyncService::QuerySyncStatusSummary() {
1378 if (HasUnrecoverableError()) {
1379 return "Unrecoverable error detected";
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001380 } else if (!backend_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001381 return "Syncing not enabled";
1382 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1383 return "First time sync setup incomplete";
1384 } else if (backend_.get() && HasSyncSetupCompleted() &&
1385 data_type_manager_.get() &&
1386 data_type_manager_->state() != DataTypeManager::CONFIGURED) {
1387 return "Datatypes not fully initialized";
1388 } else if (ShouldPushChanges()) {
1389 return "Sync service initialized";
1390 } else {
1391 return "Status unknown: Internal error?";
1392 }
1393}
1394
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001395std::string ProfileSyncService::GetBackendInitializationStateString() const {
1396 if (sync_initialized())
1397 return "Done";
1398 else if (!start_up_time_.is_null())
1399 return "Deferred";
1400 else
1401 return "Not started";
1402}
1403
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001404bool ProfileSyncService::QueryDetailedSyncStatus(
1405 SyncBackendHost::Status* result) {
1406 if (backend_.get() && backend_initialized_) {
1407 *result = backend_->GetDetailedStatus();
1408 return true;
1409 } else {
1410 SyncBackendHost::Status status;
1411 status.sync_protocol_error = last_actionable_error_;
1412 *result = status;
1413 return false;
1414 }
1415}
1416
1417const AuthError& ProfileSyncService::GetAuthError() const {
1418 return last_auth_error_;
1419}
1420
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001421GoogleServiceAuthError ProfileSyncService::GetAuthStatus() const {
1422 return GetAuthError();
1423}
1424
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001425bool ProfileSyncService::FirstSetupInProgress() const {
1426 return !HasSyncSetupCompleted() && setup_in_progress_;
1427}
1428
1429void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001430 // This method is a no-op if |setup_in_progress_| remains unchanged.
1431 if (setup_in_progress_ == setup_in_progress)
1432 return;
1433
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001434 setup_in_progress_ = setup_in_progress;
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001435 if (!setup_in_progress && sync_initialized())
1436 ReconfigureDatatypeManager();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001437 NotifyObservers();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001438}
1439
1440bool ProfileSyncService::sync_initialized() const {
1441 return backend_initialized_;
1442}
1443
1444bool ProfileSyncService::waiting_for_auth() const {
1445 return is_auth_in_progress_;
1446}
1447
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001448const syncer::Experiments& ProfileSyncService::current_experiments() const {
1449 return current_experiments_;
1450}
1451
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001452bool ProfileSyncService::HasUnrecoverableError() const {
1453 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1454}
1455
1456bool ProfileSyncService::IsPassphraseRequired() const {
1457 return passphrase_required_reason_ !=
1458 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1459}
1460
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001461bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1462 // If there is an encrypted datatype enabled and we don't have the proper
1463 // passphrase, we must prompt the user for a passphrase. The only way for the
1464 // user to avoid entering their passphrase is to disable the encrypted types.
1465 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1466}
1467
1468string16 ProfileSyncService::GetLastSyncedTimeString() const {
1469 if (last_synced_time_.is_null())
1470 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1471
1472 base::TimeDelta last_synced = base::Time::Now() - last_synced_time_;
1473
1474 if (last_synced < base::TimeDelta::FromMinutes(1))
1475 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1476
Ben Murdochbb1529c2013-08-08 10:24:53 +01001477 return ui::TimeFormat::TimeElapsed(last_synced);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001478}
1479
1480void ProfileSyncService::UpdateSelectedTypesHistogram(
1481 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1482 if (!HasSyncSetupCompleted() ||
1483 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1484 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1485 }
1486
1487 // Only log the data types that are shown in the sync settings ui.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001488 // Note: the order of these types must match the ordering of
1489 // the respective types in ModelType
1490const browser_sync::user_selectable_type::UserSelectableSyncType
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001491 user_selectable_types[] = {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001492 browser_sync::user_selectable_type::BOOKMARKS,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001493 browser_sync::user_selectable_type::PREFERENCES,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001494 browser_sync::user_selectable_type::PASSWORDS,
1495 browser_sync::user_selectable_type::AUTOFILL,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001496 browser_sync::user_selectable_type::THEMES,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001497 browser_sync::user_selectable_type::TYPED_URLS,
1498 browser_sync::user_selectable_type::EXTENSIONS,
1499 browser_sync::user_selectable_type::APPS,
1500 browser_sync::user_selectable_type::PROXY_TABS
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001501 };
1502
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01001503 COMPILE_ASSERT(28 == syncer::MODEL_TYPE_COUNT, UpdateCustomConfigHistogram);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001504
1505 if (!sync_everything) {
1506 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001507
1508 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1509 syncer::ModelTypeSet::Iterator it = type_set.First();
1510
1511 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1512
1513 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1514 ++i, it.Inc()) {
1515 const syncer::ModelType type = it.Get();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001516 if (chosen_types.Has(type) &&
1517 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1518 // Selected type has changed - log it.
1519 UMA_HISTOGRAM_ENUMERATION(
1520 "Sync.CustomSync",
1521 user_selectable_types[i],
1522 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1523 }
1524 }
1525 }
1526}
1527
1528#if defined(OS_CHROMEOS)
1529void ProfileSyncService::RefreshSpareBootstrapToken(
1530 const std::string& passphrase) {
1531 browser_sync::ChromeEncryptor encryptor;
1532 syncer::Cryptographer temp_cryptographer(&encryptor);
1533 // The first 2 params (hostname and username) doesn't have any effect here.
1534 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1535
1536 std::string bootstrap_token;
1537 if (!temp_cryptographer.AddKey(key_params)) {
1538 NOTREACHED() << "Failed to add key to cryptographer.";
1539 }
1540 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1541 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1542}
1543#endif
1544
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001545void ProfileSyncService::OnUserChoseDatatypes(
1546 bool sync_everything,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001547 syncer::ModelTypeSet chosen_types) {
1548 if (!backend_.get() && !HasUnrecoverableError()) {
1549 NOTREACHED();
1550 return;
1551 }
1552
1553 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1554 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1555
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001556 failed_data_types_handler_.Reset();
1557 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES) &&
1558 encrypted_types_.Has(syncer::SESSIONS)) {
1559 DisableBrokenDatatype(syncer::HISTORY_DELETE_DIRECTIVES,
1560 FROM_HERE,
1561 "Delete directives not supported with encryption.");
1562 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001563 ChangePreferredDataTypes(chosen_types);
1564 AcknowledgeSyncedTypes();
1565 NotifyObservers();
1566}
1567
1568void ProfileSyncService::ChangePreferredDataTypes(
1569 syncer::ModelTypeSet preferred_types) {
1570
1571 DVLOG(1) << "ChangePreferredDataTypes invoked";
1572 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1573 const syncer::ModelTypeSet registered_preferred_types =
1574 Intersection(registered_types, preferred_types);
1575 sync_prefs_.SetPreferredDataTypes(registered_types,
1576 registered_preferred_types);
1577
1578 // Now reconfigure the DTM.
1579 ReconfigureDatatypeManager();
1580}
1581
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001582syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1583 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1584 const syncer::ModelTypeSet failed_types =
1585 failed_data_types_handler_.GetFailedTypes();
1586 return Difference(preferred_types, failed_types);
1587}
1588
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001589syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1590 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1591 const syncer::ModelTypeSet preferred_types =
1592 sync_prefs_.GetPreferredDataTypes(registered_types);
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001593 return preferred_types;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001594}
1595
1596syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1597 syncer::ModelTypeSet registered_types;
1598 // The data_type_controllers_ are determined by command-line flags; that's
1599 // effectively what controls the values returned here.
1600 for (DataTypeController::TypeMap::const_iterator it =
1601 data_type_controllers_.begin();
1602 it != data_type_controllers_.end(); ++it) {
1603 registered_types.Put(it->first);
1604 }
1605 return registered_types;
1606}
1607
1608bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1609 syncer::PassphraseType passphrase_type = GetPassphraseType();
1610 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1611 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1612}
1613
1614syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1615 return backend_->GetPassphraseType();
1616}
1617
1618base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1619 return backend_->GetExplicitPassphraseTime();
1620}
1621
1622bool ProfileSyncService::IsCryptographerReady(
1623 const syncer::BaseTransaction* trans) const {
1624 return backend_.get() && backend_->IsCryptographerReady(trans);
1625}
1626
1627SyncBackendHost* ProfileSyncService::GetBackendForTest() {
1628 // We don't check |backend_initialized_|; we assume the test class
1629 // knows what it's doing.
1630 return backend_.get();
1631}
1632
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001633void ProfileSyncService::ConfigurePriorityDataTypes() {
1634 const syncer::ModelTypeSet priority_types =
1635 Intersection(GetPreferredDataTypes(), syncer::PriorityUserTypes());
1636 if (!priority_types.Empty()) {
1637 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1638 syncer::CONFIGURE_REASON_RECONFIGURATION :
1639 syncer::CONFIGURE_REASON_NEW_CLIENT;
1640 data_type_manager_->Configure(priority_types, reason);
1641 }
1642}
1643
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001644void ProfileSyncService::ConfigureDataTypeManager() {
1645 // Don't configure datatypes if the setup UI is still on the screen - this
1646 // is to help multi-screen setting UIs (like iOS) where they don't want to
1647 // start syncing data until the user is done configuring encryption options,
1648 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1649 // SetSetupInProgress(false).
1650 if (setup_in_progress_)
1651 return;
1652
1653 bool restart = false;
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001654 if (!data_type_manager_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001655 restart = true;
1656 data_type_manager_.reset(
1657 factory_->CreateDataTypeManager(debug_info_listener_,
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001658 &data_type_controllers_,
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001659 this,
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001660 backend_.get(),
1661 this,
1662 &failed_data_types_handler_));
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001663
1664 // We create the migrator at the same time.
1665 migrator_.reset(
1666 new browser_sync::BackendMigrator(
1667 profile_->GetDebugName(), GetUserShare(),
1668 this, data_type_manager_.get(),
1669 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1670 base::Unretained(this))));
1671 }
1672
1673 const syncer::ModelTypeSet types = GetPreferredDataTypes();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001674 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1675 if (!HasSyncSetupCompleted()) {
1676 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1677 } else if (restart) {
1678 // Datatype downloads on restart are generally due to newly supported
1679 // datatypes (although it's also possible we're picking up where a failed
1680 // previous configuration left off).
1681 // TODO(sync): consider detecting configuration recovery and setting
1682 // the reason here appropriately.
1683 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1684 } else {
1685 // The user initiated a reconfiguration (either to add or remove types).
1686 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1687 }
1688
1689 data_type_manager_->Configure(types, reason);
1690}
1691
1692syncer::UserShare* ProfileSyncService::GetUserShare() const {
1693 if (backend_.get() && backend_initialized_) {
1694 return backend_->GetUserShare();
1695 }
1696 NOTREACHED();
1697 return NULL;
1698}
1699
1700syncer::sessions::SyncSessionSnapshot
1701 ProfileSyncService::GetLastSessionSnapshot() const {
1702 if (backend_.get() && backend_initialized_) {
1703 return backend_->GetLastSessionSnapshot();
1704 }
1705 NOTREACHED();
1706 return syncer::sessions::SyncSessionSnapshot();
1707}
1708
1709bool ProfileSyncService::HasUnsyncedItems() const {
1710 if (backend_.get() && backend_initialized_) {
1711 return backend_->HasUnsyncedItems();
1712 }
1713 NOTREACHED();
1714 return false;
1715}
1716
1717browser_sync::BackendMigrator*
1718 ProfileSyncService::GetBackendMigratorForTest() {
1719 return migrator_.get();
1720}
1721
1722void ProfileSyncService::GetModelSafeRoutingInfo(
1723 syncer::ModelSafeRoutingInfo* out) const {
1724 if (backend_.get() && backend_initialized_) {
1725 backend_->GetModelSafeRoutingInfo(out);
1726 } else {
1727 NOTREACHED();
1728 }
1729}
1730
1731Value* ProfileSyncService::GetTypeStatusMap() const {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001732 scoped_ptr<ListValue> result(new ListValue());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001733
1734 if (!backend_.get() || !backend_initialized_) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001735 return result.release();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001736 }
1737
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001738 FailedDataTypesHandler::TypeErrorMap error_map =
1739 failed_data_types_handler_.GetAllErrors();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001740
1741 ModelTypeSet active_types;
1742 ModelTypeSet passive_types;
1743 ModelSafeRoutingInfo routing_info;
1744 backend_->GetModelSafeRoutingInfo(&routing_info);
1745 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1746 it != routing_info.end(); ++it) {
1747 if (it->second == syncer::GROUP_PASSIVE) {
1748 passive_types.Put(it->first);
1749 } else {
1750 active_types.Put(it->first);
1751 }
1752 }
1753
1754 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
1755 ModelTypeSet &throttled_types(detailed_status.throttled_types);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001756 ModelTypeSet registered = GetRegisteredDataTypes();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001757 scoped_ptr<DictionaryValue> type_status_header(new DictionaryValue());
1758
1759 type_status_header->SetString("name", "Model Type");
1760 type_status_header->SetString("status", "header");
1761 type_status_header->SetString("value", "Group Type");
1762 type_status_header->SetString("num_entries", "Total Entries");
1763 type_status_header->SetString("num_live", "Live Entries");
1764 result->Append(type_status_header.release());
1765
1766 scoped_ptr<DictionaryValue> type_status;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001767 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
1768 ModelType type = it.Get();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001769
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001770 type_status.reset(new DictionaryValue());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001771 type_status->SetString("name", ModelTypeToString(type));
1772
1773 if (error_map.find(type) != error_map.end()) {
1774 const syncer::SyncError &error = error_map.find(type)->second;
1775 DCHECK(error.IsSet());
1776 std::string error_text = "Error: " + error.location().ToString() +
1777 ", " + error.message();
1778 type_status->SetString("status", "error");
1779 type_status->SetString("value", error_text);
1780 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
1781 type_status->SetString("status", "warning");
1782 type_status->SetString("value", "Passive, Throttled");
1783 } else if (passive_types.Has(type)) {
1784 type_status->SetString("status", "warning");
1785 type_status->SetString("value", "Passive");
1786 } else if (throttled_types.Has(type)) {
1787 type_status->SetString("status", "warning");
1788 type_status->SetString("value", "Throttled");
1789 } else if (active_types.Has(type)) {
1790 type_status->SetString("status", "ok");
1791 type_status->SetString("value", "Active: " +
1792 ModelSafeGroupToString(routing_info[type]));
1793 } else {
1794 type_status->SetString("status", "warning");
1795 type_status->SetString("value", "Disabled by User");
1796 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001797
1798 int live_count = detailed_status.num_entries_by_type[type] -
1799 detailed_status.num_to_delete_entries_by_type[type];
1800 type_status->SetInteger("num_entries",
1801 detailed_status.num_entries_by_type[type]);
1802 type_status->SetInteger("num_live", live_count);
1803
1804 result->Append(type_status.release());
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001805 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001806 return result.release();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001807}
1808
1809void ProfileSyncService::ActivateDataType(
1810 syncer::ModelType type, syncer::ModelSafeGroup group,
1811 ChangeProcessor* change_processor) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001812 if (!backend_) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001813 NOTREACHED();
1814 return;
1815 }
1816 DCHECK(backend_initialized_);
1817 backend_->ActivateDataType(type, group, change_processor);
1818}
1819
1820void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01001821 if (!backend_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001822 return;
1823 backend_->DeactivateDataType(type);
1824}
1825
1826void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
1827 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
1828 // If the backend isn't running yet, OnBackendInitialized() will call this
1829 // method again after the backend starts up.
1830 if (cached_passphrase_.empty() || !sync_initialized())
1831 return;
1832
1833 // Backend is up and running, so we can consume the cached passphrase.
1834 std::string passphrase = cached_passphrase_;
1835 cached_passphrase_.clear();
1836
1837 // If we need a passphrase to decrypt data, try the cached passphrase.
1838 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
1839 if (SetDecryptionPassphrase(passphrase)) {
1840 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
1841 return;
1842 }
1843 }
1844
1845 // If we get here, we don't have pending keys (or at least, the passphrase
1846 // doesn't decrypt them) - just try to re-encrypt using the encryption
1847 // passphrase.
1848 if (!IsUsingSecondaryPassphrase())
1849 SetEncryptionPassphrase(passphrase, IMPLICIT);
1850}
1851
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001852void ProfileSyncService::RequestAccessToken() {
1853 // Only one active request at a time.
1854 if (access_token_request_ != NULL)
1855 return;
1856 request_access_token_retry_timer_.Stop();
1857 OAuth2TokenService::ScopeSet oauth2_scopes;
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01001858 if (profile_->IsManaged()) {
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001859 oauth2_scopes.insert(GaiaConstants::kChromeSyncManagedOAuth2Scope);
Ben Murdocheb525c52013-07-10 11:40:50 +01001860 } else {
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001861 oauth2_scopes.insert(GaiaConstants::kChromeSyncOAuth2Scope);
Ben Murdocheb525c52013-07-10 11:40:50 +01001862 }
1863
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001864 OAuth2TokenService* token_service =
1865 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
1866 // Invalidate previous token, otherwise token service will return the same
1867 // token again.
Ben Murdoch7dbb3d52013-07-17 14:55:54 +01001868 if (!access_token_.empty())
1869 token_service->InvalidateToken(oauth2_scopes, access_token_);
Torne (Richard Coles)7d4cd472013-06-19 11:58:07 +01001870 access_token_.clear();
1871 access_token_request_ = token_service->StartRequest(oauth2_scopes, this);
1872}
1873
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001874void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
1875 PassphraseType type) {
1876 // This should only be called when the backend has been initialized.
1877 DCHECK(sync_initialized());
1878 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
1879 "Data is already encrypted using an explicit passphrase";
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001880 DCHECK(!(type == EXPLICIT &&
1881 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
1882 "Can not set explicit passphrase when decryption is needed.";
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001883
1884 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
1885 << " passphrase for encryption.";
1886 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
1887 // REASON_ENCRYPTION implies that the cryptographer does not have pending
1888 // keys. Hence, as long as we're not trying to do an invalid passphrase
1889 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
1890 // will succeed. If for some reason a new encryption key arrives via
1891 // sync later, the SBH will trigger another OnPassphraseRequired().
1892 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1893 NotifyObservers();
1894 }
1895 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
1896}
1897
1898bool ProfileSyncService::SetDecryptionPassphrase(
1899 const std::string& passphrase) {
1900 if (IsPassphraseRequired()) {
1901 DVLOG(1) << "Setting passphrase for decryption.";
1902 return backend_->SetDecryptionPassphrase(passphrase);
1903 } else {
1904 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
1905 "IsPassphraseRequired() is false.";
1906 return false;
1907 }
1908}
1909
1910void ProfileSyncService::EnableEncryptEverything() {
1911 // Tests override sync_initialized() to always return true, so we
1912 // must check that instead of |backend_initialized_|.
1913 // TODO(akalin): Fix the above. :/
1914 DCHECK(sync_initialized());
1915 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
1916 // problems around cancelling encryption in the background (crbug.com/119649).
1917 if (!encrypt_everything_)
1918 encryption_pending_ = true;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001919}
1920
1921bool ProfileSyncService::encryption_pending() const {
1922 // We may be called during the setup process before we're
1923 // initialized (via IsEncryptedDatatypeEnabled and
1924 // IsPassphraseRequiredForDecryption).
1925 return encryption_pending_;
1926}
1927
1928bool ProfileSyncService::EncryptEverythingEnabled() const {
1929 DCHECK(backend_initialized_);
1930 return encrypt_everything_ || encryption_pending_;
1931}
1932
1933syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
1934 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1935 // We may be called during the setup process before we're
1936 // initialized. In this case, we default to the sensitive types.
1937 return encrypted_types_;
1938}
1939
1940void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
1941 NotifyObservers();
1942 if (is_sync_managed) {
1943 DisableForUser();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001944 } else {
1945 // Sync is no longer disabled by policy. Try starting it up if appropriate.
1946 TryStart();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001947 }
1948}
1949
1950void ProfileSyncService::Observe(int type,
1951 const content::NotificationSource& source,
1952 const content::NotificationDetails& details) {
1953 switch (type) {
1954 case chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL: {
1955 const GoogleServiceSigninSuccessDetails* successful =
1956 content::Details<const GoogleServiceSigninSuccessDetails>(
1957 details).ptr();
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001958 if (!sync_prefs_.IsStartSuppressed() &&
1959 !successful->password.empty()) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001960 cached_passphrase_ = successful->password;
1961 // Try to consume the passphrase we just cached. If the sync backend
1962 // is not running yet, the passphrase will remain cached until the
1963 // backend starts up.
1964 ConsumeCachedPassphraseIfPossible();
1965 }
1966#if defined(OS_CHROMEOS)
1967 RefreshSpareBootstrapToken(successful->password);
1968#endif
1969 if (!sync_initialized() ||
1970 GetAuthError().state() != AuthError::NONE) {
1971 // Track the fact that we're still waiting for auth to complete.
1972 is_auth_in_progress_ = true;
1973 }
1974 break;
1975 }
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001976 case chrome::NOTIFICATION_GOOGLE_SIGNED_OUT:
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01001977 sync_disabled_by_admin_ = false;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00001978 DisableForUser();
1979 break;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001980 default: {
1981 NOTREACHED();
1982 }
1983 }
1984}
1985
Ben Murdochca12bfa2013-07-23 11:17:05 +01001986void ProfileSyncService::AddObserver(
1987 ProfileSyncServiceBase::Observer* observer) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001988 observers_.AddObserver(observer);
1989}
1990
Ben Murdochca12bfa2013-07-23 11:17:05 +01001991void ProfileSyncService::RemoveObserver(
1992 ProfileSyncServiceBase::Observer* observer) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001993 observers_.RemoveObserver(observer);
1994}
1995
Ben Murdochca12bfa2013-07-23 11:17:05 +01001996bool ProfileSyncService::HasObserver(
1997 ProfileSyncServiceBase::Observer* observer) const {
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001998 return observers_.HasObserver(observer);
1999}
2000
2001base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2002 return sync_js_controller_.AsWeakPtr();
2003}
2004
2005void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2006 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2007}
2008
2009// static
2010bool ProfileSyncService::IsSyncEnabled() {
2011 // We have switches::kEnableSync just in case we need to change back to
2012 // sync-disabled-by-default on a platform.
2013 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync);
2014}
2015
2016bool ProfileSyncService::IsManaged() const {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002017 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002018}
2019
2020bool ProfileSyncService::ShouldPushChanges() {
2021 // True only after all bootstrapping has succeeded: the sync backend
2022 // is initialized, all enabled data types are consistent with one
2023 // another, and no unrecoverable error has transpired.
2024 if (HasUnrecoverableError())
2025 return false;
2026
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +01002027 if (!data_type_manager_)
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002028 return false;
2029
2030 return data_type_manager_->state() == DataTypeManager::CONFIGURED;
2031}
2032
2033void ProfileSyncService::StopAndSuppress() {
2034 sync_prefs_.SetStartSuppressed(true);
Ben Murdochca12bfa2013-07-23 11:17:05 +01002035 if (backend_) {
2036 backend_->UnregisterInvalidationIds();
2037 }
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002038 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD);
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002039}
2040
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +00002041bool ProfileSyncService::IsStartSuppressed() const {
2042 return sync_prefs_.IsStartSuppressed();
2043}
2044
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002045void ProfileSyncService::UnsuppressAndStart() {
2046 DCHECK(profile_);
2047 sync_prefs_.SetStartSuppressed(false);
2048 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess
2049 // is never called for some clients.
2050 if (signin_ && signin_->GetAuthenticatedUsername().empty()) {
2051 signin_->SetAuthenticatedUsername(sync_prefs_.GetGoogleServicesUsername());
2052 }
2053 TryStart();
2054}
2055
2056void ProfileSyncService::AcknowledgeSyncedTypes() {
2057 sync_prefs_.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2058}
2059
2060void ProfileSyncService::ReconfigureDatatypeManager() {
2061 // If we haven't initialized yet, don't configure the DTM as it could cause
2062 // association to start before a Directory has even been created.
2063 if (backend_initialized_) {
2064 DCHECK(backend_.get());
2065 ConfigureDataTypeManager();
2066 } else if (HasUnrecoverableError()) {
2067 // There is nothing more to configure. So inform the listeners,
2068 NotifyObservers();
2069
2070 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2071 << "Unrecoverable error.";
2072 } else {
2073 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2074 << "initialized";
2075 }
2076}
2077
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002078const FailedDataTypesHandler& ProfileSyncService::failed_data_types_handler()
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002079 const {
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +01002080 return failed_data_types_handler_;
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002081}
2082
2083void ProfileSyncService::OnInternalUnrecoverableError(
2084 const tracked_objects::Location& from_here,
2085 const std::string& message,
2086 bool delete_sync_database,
2087 UnrecoverableErrorReason reason) {
2088 DCHECK(!HasUnrecoverableError());
2089 unrecoverable_error_reason_ = reason;
2090 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2091}
2092
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002093std::string ProfileSyncService::GetEffectiveUsername() {
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002094 if (profile_->IsManaged()) {
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002095#if defined(ENABLE_MANAGED_USERS)
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002096 DCHECK_EQ(std::string(), signin_->GetAuthenticatedUsername());
2097 return ManagedUserService::GetManagedUserPseudoEmail();
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002098#else
2099 NOTREACHED();
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002100#endif
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002101 }
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002102
Torne (Richard Coles)90dce4d2013-05-29 14:40:03 +01002103 return signin_->GetAuthenticatedUsername();
Torne (Richard Coles)58218062012-11-14 11:43:16 +00002104}
Torne (Richard Coles)a36e5922013-08-05 13:57:33 +01002105
2106WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2107 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2108}