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_CORE_H_
6#define CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_
7
8#include "base/memory/ref_counted.h"
9
10#include "base/timer/timer.h"
11#include "chrome/browser/sync/glue/sync_backend_host_impl.h"
12#include "components/sync_driver/system_encryptor.h"
13#include "sync/internal_api/public/base/cancelation_signal.h"
14#include "sync/internal_api/public/sessions/type_debug_info_observer.h"
15#include "sync/internal_api/public/shutdown_reason.h"
16#include "sync/internal_api/public/sync_encryption_handler.h"
17#include "url/gurl.h"
18
19namespace browser_sync {
20
21class SyncBackendHostImpl;
22
23// Utility struct for holding initialization options.
24struct DoInitializeOptions {
25  DoInitializeOptions(
26      base::MessageLoop* sync_loop,
27      SyncBackendRegistrar* registrar,
28      const syncer::ModelSafeRoutingInfo& routing_info,
29      const std::vector<scoped_refptr<syncer::ModelSafeWorker> >& workers,
30      const scoped_refptr<syncer::ExtensionsActivity>& extensions_activity,
31      const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
32      const GURL& service_url,
33      scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory,
34      const syncer::SyncCredentials& credentials,
35      const std::string& invalidator_client_id,
36      scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
37      bool delete_sync_data_folder,
38      const std::string& restored_key_for_bootstrapping,
39      const std::string& restored_keystore_key_for_bootstrapping,
40      scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory,
41      scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
42      syncer::ReportUnrecoverableErrorFunction
43          report_unrecoverable_error_function);
44  ~DoInitializeOptions();
45
46  base::MessageLoop* sync_loop;
47  SyncBackendRegistrar* registrar;
48  syncer::ModelSafeRoutingInfo routing_info;
49  std::vector<scoped_refptr<syncer::ModelSafeWorker> > workers;
50  scoped_refptr<syncer::ExtensionsActivity> extensions_activity;
51  syncer::WeakHandle<syncer::JsEventHandler> event_handler;
52  GURL service_url;
53  // Overridden by tests.
54  scoped_ptr<syncer::HttpPostProviderFactory> http_bridge_factory;
55  syncer::SyncCredentials credentials;
56  const std::string invalidator_client_id;
57  scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory;
58  std::string lsid;
59  bool delete_sync_data_folder;
60  std::string restored_key_for_bootstrapping;
61  std::string restored_keystore_key_for_bootstrapping;
62  scoped_ptr<syncer::InternalComponentsFactory> internal_components_factory;
63  scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler;
64  syncer::ReportUnrecoverableErrorFunction
65      report_unrecoverable_error_function;
66};
67
68// Helper struct to handle currying params to
69// SyncBackendHost::Core::DoConfigureSyncer.
70struct DoConfigureSyncerTypes {
71  DoConfigureSyncerTypes();
72  ~DoConfigureSyncerTypes();
73  syncer::ModelTypeSet to_download;
74  syncer::ModelTypeSet to_purge;
75  syncer::ModelTypeSet to_journal;
76  syncer::ModelTypeSet to_unapply;
77};
78
79class SyncBackendHostCore
80    : public base::RefCountedThreadSafe<SyncBackendHostCore>,
81      public syncer::SyncEncryptionHandler::Observer,
82      public syncer::SyncManager::Observer,
83      public syncer::TypeDebugInfoObserver {
84 public:
85  SyncBackendHostCore(const std::string& name,
86       const base::FilePath& sync_data_folder_path,
87       bool has_sync_setup_completed,
88       const base::WeakPtr<SyncBackendHostImpl>& backend);
89
90  // SyncManager::Observer implementation.  The Core just acts like an air
91  // traffic controller here, forwarding incoming messages to appropriate
92  // landing threads.
93  virtual void OnSyncCycleCompleted(
94      const syncer::sessions::SyncSessionSnapshot& snapshot) OVERRIDE;
95  virtual void OnInitializationComplete(
96      const syncer::WeakHandle<syncer::JsBackend>& js_backend,
97      const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
98          debug_info_listener,
99      bool success,
100      syncer::ModelTypeSet restored_types) OVERRIDE;
101  virtual void OnConnectionStatusChange(
102      syncer::ConnectionStatus status) OVERRIDE;
103  virtual void OnActionableError(
104      const syncer::SyncProtocolError& sync_error) OVERRIDE;
105  virtual void OnMigrationRequested(syncer::ModelTypeSet types) OVERRIDE;
106  virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE;
107
108  // SyncEncryptionHandler::Observer implementation.
109  virtual void OnPassphraseRequired(
110      syncer::PassphraseRequiredReason reason,
111      const sync_pb::EncryptedData& pending_keys) OVERRIDE;
112  virtual void OnPassphraseAccepted() OVERRIDE;
113  virtual void OnBootstrapTokenUpdated(
114      const std::string& bootstrap_token,
115      syncer::BootstrapTokenType type) OVERRIDE;
116  virtual void OnEncryptedTypesChanged(
117      syncer::ModelTypeSet encrypted_types,
118      bool encrypt_everything) OVERRIDE;
119  virtual void OnEncryptionComplete() OVERRIDE;
120  virtual void OnCryptographerStateChanged(
121      syncer::Cryptographer* cryptographer) OVERRIDE;
122  virtual void OnPassphraseTypeChanged(syncer::PassphraseType type,
123                                       base::Time passphrase_time) OVERRIDE;
124
125  // TypeDebugInfoObserver implementation
126  virtual void OnCommitCountersUpdated(
127      syncer::ModelType type,
128      const syncer::CommitCounters& counters) OVERRIDE;
129  virtual void OnUpdateCountersUpdated(
130      syncer::ModelType type,
131      const syncer::UpdateCounters& counters) OVERRIDE;
132  virtual void OnStatusCountersUpdated(
133      syncer::ModelType type,
134      const syncer::StatusCounters& counters) OVERRIDE;
135
136  // Forwards an invalidation state change to the sync manager.
137  void DoOnInvalidatorStateChange(syncer::InvalidatorState state);
138
139  // Forwards an invalidation to the sync manager.
140  void DoOnIncomingInvalidation(
141      const syncer::ObjectIdInvalidationMap& invalidation_map);
142
143  // Note:
144  //
145  // The Do* methods are the various entry points from our
146  // SyncBackendHost.  They are all called on the sync thread to
147  // actually perform synchronous (and potentially blocking) syncapi
148  // operations.
149  //
150  // Called to perform initialization of the syncapi on behalf of
151  // SyncBackendHost::Initialize.
152  void DoInitialize(scoped_ptr<DoInitializeOptions> options);
153
154  // Called to perform credential update on behalf of
155  // SyncBackendHost::UpdateCredentials.
156  void DoUpdateCredentials(const syncer::SyncCredentials& credentials);
157
158  // Called to tell the syncapi to start syncing (generally after
159  // initialization and authentication).
160  void DoStartSyncing(const syncer::ModelSafeRoutingInfo& routing_info);
161
162  // Called to set the passphrase for encryption.
163  void DoSetEncryptionPassphrase(const std::string& passphrase,
164                                 bool is_explicit);
165
166  // Called to decrypt the pending keys.
167  void DoSetDecryptionPassphrase(const std::string& passphrase);
168
169  // Called to turn on encryption of all sync data as well as
170  // reencrypt everything.
171  void DoEnableEncryptEverything();
172
173  // Ask the syncer to check for updates for the specified types.
174  void DoRefreshTypes(syncer::ModelTypeSet types);
175
176  // Invoked if we failed to download the necessary control types at startup.
177  // Invokes SyncBackendHost::HandleControlTypesDownloadRetry.
178  void OnControlTypesDownloadRetry();
179
180  // Called to perform tasks which require the control data to be downloaded.
181  // This includes refreshing encryption, etc.
182  void DoInitialProcessControlTypes();
183
184  // The shutdown order is a bit complicated:
185  // 1) Call ShutdownOnUIThread() from |frontend_loop_| to request sync manager
186  //    to stop as soon as possible.
187  // 2) Post DoShutdown() to sync loop to clean up backend state, save
188  //    directory and destroy sync manager.
189  void ShutdownOnUIThread();
190  void DoShutdown(syncer::ShutdownReason reason);
191  void DoDestroySyncManager(syncer::ShutdownReason reason);
192
193  // Configuration methods that must execute on sync loop.
194  void DoConfigureSyncer(
195      syncer::ConfigureReason reason,
196      const DoConfigureSyncerTypes& config_types,
197      const syncer::ModelSafeRoutingInfo routing_info,
198      const base::Callback<void(syncer::ModelTypeSet,
199                                syncer::ModelTypeSet)>& ready_task,
200      const base::Closure& retry_callback);
201  void DoFinishConfigureDataTypes(
202      syncer::ModelTypeSet types_to_config,
203      const base::Callback<void(syncer::ModelTypeSet,
204                                syncer::ModelTypeSet)>& ready_task);
205  void DoRetryConfiguration(
206      const base::Closure& retry_callback);
207
208  // Set the base request context to use when making HTTP calls.
209  // This method will add a reference to the context to persist it
210  // on the IO thread. Must be removed from IO thread.
211
212  syncer::SyncManager* sync_manager() { return sync_manager_.get(); }
213
214  void SendBufferedProtocolEventsAndEnableForwarding();
215  void DisableProtocolEventForwarding();
216
217  // Enables the forwarding of directory type debug counters to the
218  // SyncBackendHost.  Also requests that updates to all counters be
219  // emitted right away to initialize any new listeners' states.
220  void EnableDirectoryTypeDebugInfoForwarding();
221
222  // Disables forwarding of directory type debug counters.
223  void DisableDirectoryTypeDebugInfoForwarding();
224
225  // Delete the sync data folder to cleanup backend data.  Happens the first
226  // time sync is enabled for a user (to prevent accidentally reusing old
227  // sync databases), as well as shutdown when you're no longer syncing.
228  void DeleteSyncDataFolder();
229
230  // We expose this member because it's required in the construction of the
231  // HttpBridgeFactory.
232  syncer::CancelationSignal* GetRequestContextCancelationSignal() {
233    return &release_request_context_signal_;
234  }
235
236  void GetAllNodesForTypes(
237      syncer::ModelTypeSet types,
238      scoped_refptr<base::SequencedTaskRunner> task_runner,
239      base::Callback<void(const std::vector<syncer::ModelType>& type,
240                          ScopedVector<base::ListValue>) > callback);
241
242 private:
243  friend class base::RefCountedThreadSafe<SyncBackendHostCore>;
244  friend class SyncBackendHostForProfileSyncTest;
245
246  virtual ~SyncBackendHostCore();
247
248  // Invoked when initialization of syncapi is complete and we can start
249  // our timer.
250  // This must be called from the thread on which SaveChanges is intended to
251  // be run on; the host's |registrar_->sync_thread()|.
252  void StartSavingChanges();
253
254  // Invoked periodically to tell the syncapi to persist its state
255  // by writing to disk.
256  // This is called from the thread we were created on (which is sync thread),
257  // using a repeating timer that is kicked off as soon as the SyncManager
258  // tells us it completed initialization.
259  void SaveChanges();
260
261  // Name used for debugging.
262  const std::string name_;
263
264  // Path of the folder that stores the sync data files.
265  const base::FilePath sync_data_folder_path_;
266
267  // Our parent SyncBackendHost.
268  syncer::WeakHandle<SyncBackendHostImpl> host_;
269
270  // The loop where all the sync backend operations happen.
271  // Non-NULL only between calls to DoInitialize() and ~Core().
272  base::MessageLoop* sync_loop_;
273
274  // Our parent's registrar (not owned).  Non-NULL only between
275  // calls to DoInitialize() and DoShutdown().
276  SyncBackendRegistrar* registrar_;
277
278  // The timer used to periodically call SaveChanges.
279  scoped_ptr<base::RepeatingTimer<SyncBackendHostCore> > save_changes_timer_;
280
281  // Our encryptor, which uses Chrome's encryption functions.
282  sync_driver::SystemEncryptor encryptor_;
283
284  // The top-level syncapi entry point.  Lives on the sync thread.
285  scoped_ptr<syncer::SyncManager> sync_manager_;
286
287  // Temporary holder of sync manager's initialization results. Set by
288  // OnInitializeComplete, and consumed when we pass it via OnBackendInitialized
289  // in the final state of HandleInitializationSuccessOnFrontendLoop.
290  syncer::WeakHandle<syncer::JsBackend> js_backend_;
291  syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_;
292
293  // These signals allow us to send requests to shut down the HttpBridgeFactory
294  // and ServerConnectionManager without having to wait for those classes to
295  // finish initializing first.
296  //
297  // See comments in SyncBackendHostCore::ShutdownOnUIThread() for more details.
298  syncer::CancelationSignal release_request_context_signal_;
299  syncer::CancelationSignal stop_syncing_signal_;
300
301  // Matches the value of SyncPref's HasSyncSetupCompleted() flag at init time.
302  // Should not be used for anything except for UMAs and logging.
303  const bool has_sync_setup_completed_;
304
305  // Set when we've been asked to forward sync protocol events to the frontend.
306  bool forward_protocol_events_;
307
308  // Set when the forwarding of per-type debug counters is enabled.
309  bool forward_type_info_;
310
311  base::WeakPtrFactory<SyncBackendHostCore> weak_ptr_factory_;
312
313  DISALLOW_COPY_AND_ASSIGN(SyncBackendHostCore);
314};
315
316}  // namespace browser_sync
317
318#endif  // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_CORE_H_
319