Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / sync / glue / sync_backend_host_impl.h
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.
4
5 #ifndef CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
6 #define CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
7
8 #include <string>
9
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"
32
33 class GURL;
34 class Profile;
35
36 namespace base {
37 class MessageLoop;
38 }
39
40 namespace invalidation {
41 class InvalidationService;
42 }
43
44 namespace syncer {
45 class NetworkResources;
46 class SyncManagerFactory;
47 }
48
49 namespace sync_driver {
50 class SyncPrefs;
51 }
52
53 namespace browser_sync {
54
55 class ChangeProcessor;
56 class SyncBackendHostCore;
57 class SyncBackendRegistrar;
58 class SyncedDeviceTracker;
59 struct DoInitializeOptions;
60
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 {
67  public:
68   typedef syncer::SyncStatus Status;
69
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
73   // |sync_prefs|.
74   SyncBackendHostImpl(const std::string& name,
75                       Profile* profile,
76                       const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs);
77   virtual ~SyncBackendHostImpl();
78
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;
129
130  protected:
131   // The types and functions below are protected so that test
132   // subclasses can use them.
133
134   // Allows tests to perform alternate core initialization work.
135   virtual void InitCore(scoped_ptr<DoInitializeOptions> options);
136
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);
150
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);
158
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);
165
166   // Downloading of control types failed and will be retried. Invokes the
167   // frontend's sync configure retry method.
168   void HandleControlTypesDownloadRetry();
169
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);
174
175   SyncFrontend* frontend() { return frontend_; }
176
177  private:
178   friend class SyncBackendHostCore;
179
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();
184
185   // Handles backend initialization failure.
186   void HandleInitializationFailureOnFrontendLoop();
187
188   // Called from Core::OnSyncCycleCompleted to handle updating frontend
189   // thread components.
190   void HandleSyncCycleCompletedOnFrontendLoop(
191       const syncer::sessions::SyncSessionSnapshot& snapshot);
192
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);
197
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
201   // storage.
202   void PersistEncryptionBootstrapToken(
203       const std::string& token,
204       syncer::BootstrapTokenType token_type);
205
206   // For convenience, checks if initialization state is INITIALIZED.
207   bool initialized() const { return initialized_; }
208
209   // Let the front end handle the actionable error event.
210   void HandleActionableErrorEventOnFrontendLoop(
211       const syncer::SyncProtocolError& sync_error);
212
213   // Handle a migration request.
214   void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types);
215
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;
222
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
228   // passed.
229   void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason,
230                                 sync_pb::EncryptedData pending_keys);
231
232   // Invoked when the passphrase provided by the user has been accepted.
233   void NotifyPassphraseAccepted();
234
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);
240
241   // Invoked when sync finishes encrypting new datatypes.
242   void NotifyEncryptionComplete();
243
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
248   // (if available).
249   void HandlePassphraseTypeChangedOnFrontendLoop(
250       syncer::PassphraseType type,
251       base::Time explicit_passphrase_time);
252
253   void HandleStopSyncingPermanentlyOnFrontendLoop();
254
255   // Dispatched to from OnConnectionStatusChange to handle updating
256   // frontend UI components.
257   void HandleConnectionStatusChangeOnFrontendLoop(
258       syncer::ConnectionStatus status);
259
260   // NotificationObserver implementation.
261   virtual void Observe(
262     int type,
263     const content::NotificationSource& source,
264     const content::NotificationDetails& details) OVERRIDE;
265
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;
272
273   content::NotificationRegistrar notification_registrar_;
274
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_;
278
279   Profile* const profile_;
280
281   // Name used for debugging (set from profile_->GetDebugName()).
282   const std::string name_;
283
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
286   // sync loop.
287   scoped_refptr<SyncBackendHostCore> core_;
288
289   bool initialized_;
290
291   const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_;
292
293   ExtensionsActivityMonitor extensions_activity_monitor_;
294
295   scoped_ptr<SyncBackendRegistrar> registrar_;
296
297   // The frontend which we serve (and are owned by).
298   SyncFrontend* frontend_;
299
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
307   // were cached.
308   sync_pb::EncryptedData cached_pending_keys_;
309
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_;
315
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_;
319
320   // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
321   syncer::sessions::SyncSessionSnapshot last_snapshot_;
322
323   invalidation::InvalidationService* invalidator_;
324   bool invalidation_handler_registered_;
325
326   base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_;
327
328   DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl);
329 };
330
331 }  // namespace browser_sync
332
333 #endif  // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_
334