1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
6 #define CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/threading/thread.h"
16 #include "chrome/browser/sync/glue/extensions_activity_monitor.h"
17 #include "chrome/browser/sync/glue/sync_backend_host.h"
18 #include "components/sync_driver/backend_data_type_configurer.h"
19 #include "content/public/browser/notification_observer.h"
20 #include "content/public/browser/notification_registrar.h"
21 #include "sync/internal_api/public/base/model_type.h"
22 #include "sync/internal_api/public/configure_reason.h"
23 #include "sync/internal_api/public/sessions/sync_session_snapshot.h"
24 #include "sync/internal_api/public/sync_manager.h"
25 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
26 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
27 #include "sync/internal_api/public/util/weak_handle.h"
28 #include "sync/notifier/invalidation_handler.h"
29 #include "sync/protocol/encryption.pb.h"
30 #include "sync/protocol/sync_protocol_error.h"
31 #include "sync/util/extensions_activity.h"
40 namespace invalidation {
41 class InvalidationService;
45 class NetworkResources;
46 class SyncManagerFactory;
49 namespace sync_driver {
53 namespace browser_sync {
55 class ChangeProcessor;
56 class SyncBackendHostCore;
57 class SyncBackendRegistrar;
58 class SyncedDeviceTracker;
59 struct DoInitializeOptions;
61 // The only real implementation of the SyncBackendHost. See that interface's
62 // definition for documentation of public methods.
63 class SyncBackendHostImpl
64 : public SyncBackendHost,
65 public content::NotificationObserver,
66 public syncer::InvalidationHandler {
68 typedef syncer::SyncStatus Status;
70 // Create a SyncBackendHost with a reference to the |frontend| that
71 // it serves and communicates to via the SyncFrontend interface (on
72 // the same thread it used to call the constructor). Must outlive
74 SyncBackendHostImpl(const std::string& name,
76 const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs);
77 virtual ~SyncBackendHostImpl();
79 // SyncBackendHost implementation.
80 virtual void Initialize(
81 SyncFrontend* frontend,
82 scoped_ptr<base::Thread> sync_thread,
83 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
84 const GURL& service_url,
85 const syncer::SyncCredentials& credentials,
86 bool delete_sync_data_folder,
87 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
88 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
89 syncer::ReportUnrecoverableErrorFunction
90 report_unrecoverable_error_function,
91 syncer::NetworkResources* network_resources) OVERRIDE;
92 virtual void UpdateCredentials(
93 const syncer::SyncCredentials& credentials) OVERRIDE;
94 virtual void StartSyncingWithServer() OVERRIDE;
95 virtual void SetEncryptionPassphrase(
96 const std::string& passphrase,
97 bool is_explicit) OVERRIDE;
98 virtual bool SetDecryptionPassphrase(const std::string& passphrase)
99 OVERRIDE WARN_UNUSED_RESULT;
100 virtual void StopSyncingForShutdown() OVERRIDE;
101 virtual scoped_ptr<base::Thread> Shutdown(ShutdownOption option) OVERRIDE;
102 virtual void UnregisterInvalidationIds() OVERRIDE;
103 virtual void ConfigureDataTypes(
104 syncer::ConfigureReason reason,
105 const DataTypeConfigStateMap& config_state_map,
106 const base::Callback<void(syncer::ModelTypeSet,
107 syncer::ModelTypeSet)>& ready_task,
108 const base::Callback<void()>& retry_callback) OVERRIDE;
109 virtual void EnableEncryptEverything() OVERRIDE;
110 virtual void ActivateDataType(
111 syncer::ModelType type, syncer::ModelSafeGroup group,
112 ChangeProcessor* change_processor) OVERRIDE;
113 virtual void DeactivateDataType(syncer::ModelType type) OVERRIDE;
114 virtual syncer::UserShare* GetUserShare() const OVERRIDE;
115 virtual Status GetDetailedStatus() OVERRIDE;
116 virtual syncer::sessions::SyncSessionSnapshot
117 GetLastSessionSnapshot() const OVERRIDE;
118 virtual bool HasUnsyncedItems() const OVERRIDE;
119 virtual bool IsNigoriEnabled() const OVERRIDE;
120 virtual syncer::PassphraseType GetPassphraseType() const OVERRIDE;
121 virtual base::Time GetExplicitPassphraseTime() const OVERRIDE;
122 virtual bool IsCryptographerReady(
123 const syncer::BaseTransaction* trans) const OVERRIDE;
124 virtual void GetModelSafeRoutingInfo(
125 syncer::ModelSafeRoutingInfo* out) const OVERRIDE;
126 virtual SyncedDeviceTracker* GetSyncedDeviceTracker() const OVERRIDE;
127 virtual void SetForwardProtocolEvents(bool forward) OVERRIDE;
128 virtual base::MessageLoop* GetSyncLoopForTesting() OVERRIDE;
131 // The types and functions below are protected so that test
132 // subclasses can use them.
134 // Allows tests to perform alternate core initialization work.
135 virtual void InitCore(scoped_ptr<DoInitializeOptions> options);
137 // Request the syncer to reconfigure with the specfied params.
138 // Virtual for testing.
139 virtual void RequestConfigureSyncer(
140 syncer::ConfigureReason reason,
141 syncer::ModelTypeSet to_download,
142 syncer::ModelTypeSet to_purge,
143 syncer::ModelTypeSet to_journal,
144 syncer::ModelTypeSet to_unapply,
145 syncer::ModelTypeSet to_ignore,
146 const syncer::ModelSafeRoutingInfo& routing_info,
147 const base::Callback<void(syncer::ModelTypeSet,
148 syncer::ModelTypeSet)>& ready_task,
149 const base::Closure& retry_callback);
151 // Called when the syncer has finished performing a configuration.
152 void FinishConfigureDataTypesOnFrontendLoop(
153 const syncer::ModelTypeSet enabled_types,
154 const syncer::ModelTypeSet succeeded_configuration_types,
155 const syncer::ModelTypeSet failed_configuration_types,
156 const base::Callback<void(syncer::ModelTypeSet,
157 syncer::ModelTypeSet)>& ready_task);
159 // Reports backend initialization success. Includes some objects from sync
160 // manager initialization to be passed back to the UI thread.
161 virtual void HandleInitializationSuccessOnFrontendLoop(
162 const syncer::WeakHandle<syncer::JsBackend> js_backend,
163 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>
164 debug_info_listener);
166 // Downloading of control types failed and will be retried. Invokes the
167 // frontend's sync configure retry method.
168 void HandleControlTypesDownloadRetry();
170 // Forwards a ProtocolEvent to the frontend. Will not be called unless a
171 // call to SetForwardProtocolEvents() explicitly requested that we start
172 // forwarding these events.
173 void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent* event);
175 SyncFrontend* frontend() { return frontend_; }
178 friend class SyncBackendHostCore;
180 // Checks if we have received a notice to turn on experimental datatypes
181 // (via the nigori node) and informs the frontend if that is the case.
182 // Note: it is illegal to call this before the backend is initialized.
183 void AddExperimentalTypes();
185 // Handles backend initialization failure.
186 void HandleInitializationFailureOnFrontendLoop();
188 // Called from Core::OnSyncCycleCompleted to handle updating frontend
189 // thread components.
190 void HandleSyncCycleCompletedOnFrontendLoop(
191 const syncer::sessions::SyncSessionSnapshot& snapshot);
193 // Called when the syncer failed to perform a configuration and will
194 // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called
195 // on successful completion.
196 void RetryConfigurationOnFrontendLoop(const base::Closure& retry_callback);
198 // Helpers to persist a token that can be used to bootstrap sync encryption
199 // across browser restart to avoid requiring the user to re-enter their
200 // passphrase. |token| must be valid UTF-8 as we use the PrefService for
202 void PersistEncryptionBootstrapToken(
203 const std::string& token,
204 syncer::BootstrapTokenType token_type);
206 // For convenience, checks if initialization state is INITIALIZED.
207 bool initialized() const { return initialized_; }
209 // Let the front end handle the actionable error event.
210 void HandleActionableErrorEventOnFrontendLoop(
211 const syncer::SyncProtocolError& sync_error);
213 // Handle a migration request.
214 void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types);
216 // Checks if |passphrase| can be used to decrypt the cryptographer's pending
217 // keys that were cached during NotifyPassphraseRequired. Returns true if
218 // decryption was successful. Returns false otherwise. Must be called with a
219 // non-empty pending keys cache.
220 bool CheckPassphraseAgainstCachedPendingKeys(
221 const std::string& passphrase) const;
223 // Invoked when a passphrase is required to decrypt a set of Nigori keys,
224 // or for encrypting. |reason| denotes why the passphrase was required.
225 // |pending_keys| is a copy of the cryptographer's pending keys, that are
226 // cached by the frontend. If there are no pending keys, or if the passphrase
227 // required reason is REASON_ENCRYPTION, an empty EncryptedData object is
229 void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason,
230 sync_pb::EncryptedData pending_keys);
232 // Invoked when the passphrase provided by the user has been accepted.
233 void NotifyPassphraseAccepted();
235 // Invoked when the set of encrypted types or the encrypt
236 // everything flag changes.
237 void NotifyEncryptedTypesChanged(
238 syncer::ModelTypeSet encrypted_types,
239 bool encrypt_everything);
241 // Invoked when sync finishes encrypting new datatypes.
242 void NotifyEncryptionComplete();
244 // Invoked when the passphrase state has changed. Caches the passphrase state
245 // for later use on the UI thread.
246 // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE,
247 // |explicit_passphrase_time| is the time at which that passphrase was set
249 void HandlePassphraseTypeChangedOnFrontendLoop(
250 syncer::PassphraseType type,
251 base::Time explicit_passphrase_time);
253 void HandleStopSyncingPermanentlyOnFrontendLoop();
255 // Dispatched to from OnConnectionStatusChange to handle updating
256 // frontend UI components.
257 void HandleConnectionStatusChangeOnFrontendLoop(
258 syncer::ConnectionStatus status);
260 // NotificationObserver implementation.
261 virtual void Observe(
263 const content::NotificationSource& source,
264 const content::NotificationDetails& details) OVERRIDE;
266 // InvalidationHandler implementation.
267 virtual void OnInvalidatorStateChange(
268 syncer::InvalidatorState state) OVERRIDE;
269 virtual void OnIncomingInvalidation(
270 const syncer::ObjectIdInvalidationMap& invalidation_map) OVERRIDE;
271 virtual std::string GetOwnerName() const OVERRIDE;
273 content::NotificationRegistrar notification_registrar_;
275 // A reference to the MessageLoop used to construct |this|, so we know how
276 // to safely talk back to the SyncFrontend.
277 base::MessageLoop* const frontend_loop_;
279 Profile* const profile_;
281 // Name used for debugging (set from profile_->GetDebugName()).
282 const std::string name_;
284 // Our core, which communicates directly to the syncapi. Use refptr instead
285 // of WeakHandle because |core_| is created on UI loop but released on
287 scoped_refptr<SyncBackendHostCore> core_;
291 const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_;
293 ExtensionsActivityMonitor extensions_activity_monitor_;
295 scoped_ptr<SyncBackendRegistrar> registrar_;
297 // The frontend which we serve (and are owned by).
298 SyncFrontend* frontend_;
300 // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
301 // is called. This way, before the UI calls SetDecryptionPassphrase on the
302 // syncer, it can avoid the overhead of an asynchronous decryption call and
303 // give the user immediate feedback about the passphrase entered by first
304 // trying to decrypt the cached pending keys on the UI thread. Note that
305 // SetDecryptionPassphrase can still fail after the cached pending keys are
306 // successfully decrypted if the pending keys have changed since the time they
308 sync_pb::EncryptedData cached_pending_keys_;
310 // The state of the passphrase required to decrypt the bag of encryption keys
311 // in the nigori node. Updated whenever a new nigori node arrives or the user
312 // manually changes their passphrase state. Cached so we can synchronously
313 // check it from the UI thread.
314 syncer::PassphraseType cached_passphrase_type_;
316 // If an explicit passphrase is in use, the time at which the passphrase was
317 // first set (if available).
318 base::Time cached_explicit_passphrase_time_;
320 // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
321 syncer::sessions::SyncSessionSnapshot last_snapshot_;
323 invalidation::InvalidationService* invalidator_;
324 bool invalidation_handler_registered_;
326 base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_;
328 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl);
331 } // namespace browser_sync
333 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_