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