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/invalidation/invalidation_handler.h"
19 #include "components/sync_driver/backend_data_type_configurer.h"
20 #include "content/public/browser/notification_observer.h"
21 #include "content/public/browser/notification_registrar.h"
22 #include "sync/internal_api/public/base/model_type.h"
23 #include "sync/internal_api/public/configure_reason.h"
24 #include "sync/internal_api/public/sessions/sync_session_snapshot.h"
25 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
26 #include "sync/internal_api/public/sync_manager.h"
27 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
28 #include "sync/internal_api/public/util/unrecoverable_error_handler.h"
29 #include "sync/internal_api/public/util/weak_handle.h"
30 #include "sync/protocol/encryption.pb.h"
31 #include "sync/protocol/sync_protocol_error.h"
32 #include "sync/util/extensions_activity.h"
41 namespace invalidation
{
42 class InvalidationService
;
46 class NetworkResources
;
47 class SyncManagerFactory
;
50 namespace sync_driver
{
54 namespace browser_sync
{
56 class ChangeProcessor
;
57 class SyncBackendHostCore
;
58 class SyncBackendRegistrar
;
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 invalidation::InvalidationService
* invalidator
,
77 const base::WeakPtr
<sync_driver::SyncPrefs
>& sync_prefs
,
78 const base::FilePath
& sync_folder
);
79 ~SyncBackendHostImpl() override
;
81 // SyncBackendHost implementation.
83 sync_driver::SyncFrontend
* frontend
,
84 scoped_ptr
<base::Thread
> sync_thread
,
85 const syncer::WeakHandle
<syncer::JsEventHandler
>& event_handler
,
86 const GURL
& service_url
,
87 const syncer::SyncCredentials
& credentials
,
88 bool delete_sync_data_folder
,
89 scoped_ptr
<syncer::SyncManagerFactory
> sync_manager_factory
,
90 scoped_ptr
<syncer::UnrecoverableErrorHandler
> unrecoverable_error_handler
,
91 syncer::ReportUnrecoverableErrorFunction
92 report_unrecoverable_error_function
,
93 syncer::NetworkResources
* network_resources
) override
;
94 void UpdateCredentials(const syncer::SyncCredentials
& credentials
) override
;
95 void StartSyncingWithServer() override
;
96 void SetEncryptionPassphrase(const std::string
& passphrase
,
97 bool is_explicit
) override
;
98 bool SetDecryptionPassphrase(const std::string
& passphrase
) override
100 void StopSyncingForShutdown() override
;
101 scoped_ptr
<base::Thread
> Shutdown(syncer::ShutdownReason reason
) override
;
102 void UnregisterInvalidationIds() override
;
103 void ConfigureDataTypes(
104 syncer::ConfigureReason reason
,
105 const DataTypeConfigStateMap
& config_state_map
,
106 const base::Callback
<void(syncer::ModelTypeSet
, syncer::ModelTypeSet
)>&
108 const base::Callback
<void()>& retry_callback
) override
;
109 void ActivateDataType(
110 syncer::ModelType type
,
111 syncer::ModelSafeGroup group
,
112 sync_driver::ChangeProcessor
* change_processor
) override
;
113 void DeactivateDataType(syncer::ModelType type
) override
;
114 void EnableEncryptEverything() override
;
115 syncer::UserShare
* GetUserShare() const override
;
116 scoped_ptr
<syncer::SyncContextProxy
> GetSyncContextProxy() override
;
117 Status
GetDetailedStatus() override
;
118 syncer::sessions::SyncSessionSnapshot
GetLastSessionSnapshot() const override
;
119 bool HasUnsyncedItems() const override
;
120 bool IsNigoriEnabled() const override
;
121 syncer::PassphraseType
GetPassphraseType() const override
;
122 base::Time
GetExplicitPassphraseTime() const override
;
123 bool IsCryptographerReady(
124 const syncer::BaseTransaction
* trans
) const override
;
125 void GetModelSafeRoutingInfo(
126 syncer::ModelSafeRoutingInfo
* out
) const override
;
127 void FlushDirectory() const override
;
128 void RequestBufferedProtocolEventsAndEnableForwarding() override
;
129 void DisableProtocolEventForwarding() override
;
130 void EnableDirectoryTypeDebugInfoForwarding() override
;
131 void DisableDirectoryTypeDebugInfoForwarding() override
;
132 void GetAllNodesForTypes(
133 syncer::ModelTypeSet types
,
134 base::Callback
<void(const std::vector
<syncer::ModelType
>&,
135 ScopedVector
<base::ListValue
>)> type
) override
;
136 base::MessageLoop
* GetSyncLoopForTesting() override
;
139 // The types and functions below are protected so that test
140 // subclasses can use them.
142 // Allows tests to perform alternate core initialization work.
143 virtual void InitCore(scoped_ptr
<DoInitializeOptions
> options
);
145 // Request the syncer to reconfigure with the specfied params.
146 // Virtual for testing.
147 virtual void RequestConfigureSyncer(
148 syncer::ConfigureReason reason
,
149 syncer::ModelTypeSet to_download
,
150 syncer::ModelTypeSet to_purge
,
151 syncer::ModelTypeSet to_journal
,
152 syncer::ModelTypeSet to_unapply
,
153 syncer::ModelTypeSet to_ignore
,
154 const syncer::ModelSafeRoutingInfo
& routing_info
,
155 const base::Callback
<void(syncer::ModelTypeSet
,
156 syncer::ModelTypeSet
)>& ready_task
,
157 const base::Closure
& retry_callback
);
159 // Called when the syncer has finished performing a configuration.
160 void FinishConfigureDataTypesOnFrontendLoop(
161 const syncer::ModelTypeSet enabled_types
,
162 const syncer::ModelTypeSet succeeded_configuration_types
,
163 const syncer::ModelTypeSet failed_configuration_types
,
164 const base::Callback
<void(syncer::ModelTypeSet
,
165 syncer::ModelTypeSet
)>& ready_task
);
167 // Reports backend initialization success. Includes some objects from sync
168 // manager initialization to be passed back to the UI thread.
170 // |sync_context_proxy| points to an object owned by the SyncManager.
171 // Ownership is not transferred, but we can obtain our own copy of the object
172 // using its Clone() method.
173 virtual void HandleInitializationSuccessOnFrontendLoop(
174 const syncer::WeakHandle
<syncer::JsBackend
> js_backend
,
175 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>
177 syncer::SyncContextProxy
* sync_context_proxy
,
178 const std::string
& cache_guid
);
180 // Forwards a ProtocolEvent to the frontend. Will not be called unless a
181 // call to SetForwardProtocolEvents() explicitly requested that we start
182 // forwarding these events.
183 void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent
* event
);
185 // Forwards a directory commit counter update to the frontend loop. Will not
186 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
187 // explicitly requested that we start forwarding these events.
188 void HandleDirectoryCommitCountersUpdatedOnFrontendLoop(
189 syncer::ModelType type
,
190 const syncer::CommitCounters
& counters
);
192 // Forwards a directory update counter update to the frontend loop. Will not
193 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
194 // explicitly requested that we start forwarding these events.
195 void HandleDirectoryUpdateCountersUpdatedOnFrontendLoop(
196 syncer::ModelType type
,
197 const syncer::UpdateCounters
& counters
);
199 // Forwards a directory status counter update to the frontend loop. Will not
200 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
201 // explicitly requested that we start forwarding these events.
202 void HandleDirectoryStatusCountersUpdatedOnFrontendLoop(
203 syncer::ModelType type
,
204 const syncer::StatusCounters
& counters
);
206 sync_driver::SyncFrontend
* frontend() { return frontend_
; }
209 friend class SyncBackendHostCore
;
211 // Checks if we have received a notice to turn on experimental datatypes
212 // (via the nigori node) and informs the frontend if that is the case.
213 // Note: it is illegal to call this before the backend is initialized.
214 void AddExperimentalTypes();
216 // Handles backend initialization failure.
217 void HandleInitializationFailureOnFrontendLoop();
219 // Called from Core::OnSyncCycleCompleted to handle updating frontend
220 // thread components.
221 void HandleSyncCycleCompletedOnFrontendLoop(
222 const syncer::sessions::SyncSessionSnapshot
& snapshot
);
224 // Called when the syncer failed to perform a configuration and will
225 // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called
226 // on successful completion.
227 void RetryConfigurationOnFrontendLoop(const base::Closure
& retry_callback
);
229 // Helpers to persist a token that can be used to bootstrap sync encryption
230 // across browser restart to avoid requiring the user to re-enter their
231 // passphrase. |token| must be valid UTF-8 as we use the PrefService for
233 void PersistEncryptionBootstrapToken(
234 const std::string
& token
,
235 syncer::BootstrapTokenType token_type
);
237 // For convenience, checks if initialization state is INITIALIZED.
238 bool initialized() const { return initialized_
; }
240 // Let the front end handle the actionable error event.
241 void HandleActionableErrorEventOnFrontendLoop(
242 const syncer::SyncProtocolError
& sync_error
);
244 // Handle a migration request.
245 void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types
);
247 // Checks if |passphrase| can be used to decrypt the cryptographer's pending
248 // keys that were cached during NotifyPassphraseRequired. Returns true if
249 // decryption was successful. Returns false otherwise. Must be called with a
250 // non-empty pending keys cache.
251 bool CheckPassphraseAgainstCachedPendingKeys(
252 const std::string
& passphrase
) const;
254 // Invoked when a passphrase is required to decrypt a set of Nigori keys,
255 // or for encrypting. |reason| denotes why the passphrase was required.
256 // |pending_keys| is a copy of the cryptographer's pending keys, that are
257 // cached by the frontend. If there are no pending keys, or if the passphrase
258 // required reason is REASON_ENCRYPTION, an empty EncryptedData object is
260 void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason
,
261 sync_pb::EncryptedData pending_keys
);
263 // Invoked when the passphrase provided by the user has been accepted.
264 void NotifyPassphraseAccepted();
266 // Invoked when the set of encrypted types or the encrypt
267 // everything flag changes.
268 void NotifyEncryptedTypesChanged(
269 syncer::ModelTypeSet encrypted_types
,
270 bool encrypt_everything
);
272 // Invoked when sync finishes encrypting new datatypes.
273 void NotifyEncryptionComplete();
275 // Invoked when the passphrase state has changed. Caches the passphrase state
276 // for later use on the UI thread.
277 // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE,
278 // |explicit_passphrase_time| is the time at which that passphrase was set
280 void HandlePassphraseTypeChangedOnFrontendLoop(
281 syncer::PassphraseType type
,
282 base::Time explicit_passphrase_time
);
284 void HandleStopSyncingPermanentlyOnFrontendLoop();
286 // Dispatched to from OnConnectionStatusChange to handle updating
287 // frontend UI components.
288 void HandleConnectionStatusChangeOnFrontendLoop(
289 syncer::ConnectionStatus status
);
291 // NotificationObserver implementation.
292 void Observe(int type
,
293 const content::NotificationSource
& source
,
294 const content::NotificationDetails
& details
) override
;
296 // InvalidationHandler implementation.
297 void OnInvalidatorStateChange(syncer::InvalidatorState state
) override
;
298 void OnIncomingInvalidation(
299 const syncer::ObjectIdInvalidationMap
& invalidation_map
) override
;
300 std::string
GetOwnerName() const override
;
302 content::NotificationRegistrar notification_registrar_
;
304 // A reference to the MessageLoop used to construct |this|, so we know how
305 // to safely talk back to the SyncFrontend.
306 base::MessageLoop
* const frontend_loop_
;
308 Profile
* const profile_
;
310 // Name used for debugging (set from profile_->GetDebugName()).
311 const std::string name_
;
313 // Our core, which communicates directly to the syncapi. Use refptr instead
314 // of WeakHandle because |core_| is created on UI loop but released on
316 scoped_refptr
<SyncBackendHostCore
> core_
;
318 // A handle referencing the main interface for non-blocking sync types.
319 scoped_ptr
<syncer::SyncContextProxy
> sync_context_proxy_
;
323 const base::WeakPtr
<sync_driver::SyncPrefs
> sync_prefs_
;
325 ExtensionsActivityMonitor extensions_activity_monitor_
;
327 scoped_ptr
<SyncBackendRegistrar
> registrar_
;
329 // The frontend which we serve (and are owned by).
330 sync_driver::SyncFrontend
* frontend_
;
332 // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
333 // is called. This way, before the UI calls SetDecryptionPassphrase on the
334 // syncer, it can avoid the overhead of an asynchronous decryption call and
335 // give the user immediate feedback about the passphrase entered by first
336 // trying to decrypt the cached pending keys on the UI thread. Note that
337 // SetDecryptionPassphrase can still fail after the cached pending keys are
338 // successfully decrypted if the pending keys have changed since the time they
340 sync_pb::EncryptedData cached_pending_keys_
;
342 // The state of the passphrase required to decrypt the bag of encryption keys
343 // in the nigori node. Updated whenever a new nigori node arrives or the user
344 // manually changes their passphrase state. Cached so we can synchronously
345 // check it from the UI thread.
346 syncer::PassphraseType cached_passphrase_type_
;
348 // If an explicit passphrase is in use, the time at which the passphrase was
349 // first set (if available).
350 base::Time cached_explicit_passphrase_time_
;
352 // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
353 syncer::sessions::SyncSessionSnapshot last_snapshot_
;
355 invalidation::InvalidationService
* invalidator_
;
356 bool invalidation_handler_registered_
;
358 base::WeakPtrFactory
<SyncBackendHostImpl
> weak_ptr_factory_
;
360 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl
);
363 } // namespace browser_sync
365 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_