Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / sync / glue / sync_backend_host_impl.h
blob21b7acb3beb0060f7b224fc05d59a2e2ea88352d
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_
8 #include <string>
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/public/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/weak_handle.h"
28 #include "sync/protocol/encryption.pb.h"
29 #include "sync/protocol/sync_protocol_error.h"
30 #include "sync/util/extensions_activity.h"
32 class GURL;
33 class Profile;
35 namespace base {
36 class MessageLoop;
39 namespace invalidation {
40 class InvalidationService;
43 namespace syncer {
44 class NetworkResources;
45 class SyncManagerFactory;
46 class UnrecoverableErrorHandler;
49 namespace sync_driver {
50 class SyncPrefs;
53 namespace browser_sync {
55 class ChangeProcessor;
56 class SyncBackendHostCore;
57 class SyncBackendRegistrar;
58 struct DoInitializeOptions;
60 // The only real implementation of the SyncBackendHost. See that interface's
61 // definition for documentation of public methods.
62 class SyncBackendHostImpl
63 : public SyncBackendHost,
64 public content::NotificationObserver,
65 public syncer::InvalidationHandler {
66 public:
67 typedef syncer::SyncStatus Status;
69 // Create a SyncBackendHost with a reference to the |frontend| that
70 // it serves and communicates to via the SyncFrontend interface (on
71 // the same thread it used to call the constructor). Must outlive
72 // |sync_prefs|.
73 SyncBackendHostImpl(const std::string& name,
74 Profile* profile,
75 invalidation::InvalidationService* invalidator,
76 const base::WeakPtr<sync_driver::SyncPrefs>& sync_prefs,
77 const base::FilePath& sync_folder);
78 ~SyncBackendHostImpl() override;
80 // SyncBackendHost implementation.
81 void Initialize(
82 sync_driver::SyncFrontend* frontend,
83 scoped_ptr<base::Thread> sync_thread,
84 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
85 const GURL& service_url,
86 const std::string& sync_user_agent,
87 const syncer::SyncCredentials& credentials,
88 bool delete_sync_data_folder,
89 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
90 const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>&
91 unrecoverable_error_handler,
92 const base::Closure& report_unrecoverable_error_function,
93 syncer::NetworkResources* network_resources,
94 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state)
95 override;
96 void UpdateCredentials(const syncer::SyncCredentials& credentials) override;
97 void StartSyncingWithServer() override;
98 void SetEncryptionPassphrase(const std::string& passphrase,
99 bool is_explicit) override;
100 bool SetDecryptionPassphrase(const std::string& passphrase) override
101 WARN_UNUSED_RESULT;
102 void StopSyncingForShutdown() override;
103 scoped_ptr<base::Thread> Shutdown(syncer::ShutdownReason reason) override;
104 void UnregisterInvalidationIds() override;
105 syncer::ModelTypeSet ConfigureDataTypes(
106 syncer::ConfigureReason reason,
107 const DataTypeConfigStateMap& config_state_map,
108 const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>&
109 ready_task,
110 const base::Callback<void()>& retry_callback) override;
111 void ActivateDataType(
112 syncer::ModelType type,
113 syncer::ModelSafeGroup group,
114 sync_driver::ChangeProcessor* change_processor) override;
115 void DeactivateDataType(syncer::ModelType type) override;
116 void EnableEncryptEverything() override;
117 syncer::UserShare* GetUserShare() const override;
118 scoped_ptr<syncer_v2::SyncContextProxy> GetSyncContextProxy() override;
119 Status GetDetailedStatus() override;
120 syncer::sessions::SyncSessionSnapshot GetLastSessionSnapshot() const override;
121 bool HasUnsyncedItems() const override;
122 bool IsNigoriEnabled() const override;
123 syncer::PassphraseType GetPassphraseType() const override;
124 base::Time GetExplicitPassphraseTime() const override;
125 bool IsCryptographerReady(
126 const syncer::BaseTransaction* trans) const override;
127 void GetModelSafeRoutingInfo(
128 syncer::ModelSafeRoutingInfo* out) const override;
129 void FlushDirectory() const override;
130 void RequestBufferedProtocolEventsAndEnableForwarding() override;
131 void DisableProtocolEventForwarding() override;
132 void EnableDirectoryTypeDebugInfoForwarding() override;
133 void DisableDirectoryTypeDebugInfoForwarding() override;
134 void GetAllNodesForTypes(
135 syncer::ModelTypeSet types,
136 base::Callback<void(const std::vector<syncer::ModelType>&,
137 ScopedVector<base::ListValue>)> type) override;
138 base::MessageLoop* GetSyncLoopForTesting() override;
139 void RefreshTypesForTest(syncer::ModelTypeSet types) override;
140 void ClearServerData(
141 const syncer::SyncManager::ClearServerDataCallback& callback) override;
143 // InvalidationHandler implementation.
144 void OnInvalidatorStateChange(syncer::InvalidatorState state) override;
145 void OnIncomingInvalidation(
146 const syncer::ObjectIdInvalidationMap& invalidation_map) override;
147 std::string GetOwnerName() const override;
149 protected:
150 // The types and functions below are protected so that test
151 // subclasses can use them.
153 // Allows tests to perform alternate core initialization work.
154 virtual void InitCore(scoped_ptr<DoInitializeOptions> options);
156 // Request the syncer to reconfigure with the specfied params.
157 // Virtual for testing.
158 virtual void RequestConfigureSyncer(
159 syncer::ConfigureReason reason,
160 syncer::ModelTypeSet to_download,
161 syncer::ModelTypeSet to_purge,
162 syncer::ModelTypeSet to_journal,
163 syncer::ModelTypeSet to_unapply,
164 syncer::ModelTypeSet to_ignore,
165 const syncer::ModelSafeRoutingInfo& routing_info,
166 const base::Callback<void(syncer::ModelTypeSet,
167 syncer::ModelTypeSet)>& ready_task,
168 const base::Closure& retry_callback);
170 // Called when the syncer has finished performing a configuration.
171 void FinishConfigureDataTypesOnFrontendLoop(
172 const syncer::ModelTypeSet enabled_types,
173 const syncer::ModelTypeSet succeeded_configuration_types,
174 const syncer::ModelTypeSet failed_configuration_types,
175 const base::Callback<void(syncer::ModelTypeSet,
176 syncer::ModelTypeSet)>& ready_task);
178 // Reports backend initialization success. Includes some objects from sync
179 // manager initialization to be passed back to the UI thread.
181 // |sync_context_proxy| points to an object owned by the SyncManager.
182 // Ownership is not transferred, but we can obtain our own copy of the object
183 // using its Clone() method.
184 virtual void HandleInitializationSuccessOnFrontendLoop(
185 const syncer::WeakHandle<syncer::JsBackend> js_backend,
186 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>
187 debug_info_listener,
188 syncer_v2::SyncContextProxy* sync_context_proxy,
189 const std::string& cache_guid);
191 // Forwards a ProtocolEvent to the frontend. Will not be called unless a
192 // call to SetForwardProtocolEvents() explicitly requested that we start
193 // forwarding these events.
194 void HandleProtocolEventOnFrontendLoop(syncer::ProtocolEvent* event);
196 // Forwards a directory commit counter update to the frontend loop. Will not
197 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
198 // explicitly requested that we start forwarding these events.
199 void HandleDirectoryCommitCountersUpdatedOnFrontendLoop(
200 syncer::ModelType type,
201 const syncer::CommitCounters& counters);
203 // Forwards a directory update counter update to the frontend loop. Will not
204 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
205 // explicitly requested that we start forwarding these events.
206 void HandleDirectoryUpdateCountersUpdatedOnFrontendLoop(
207 syncer::ModelType type,
208 const syncer::UpdateCounters& counters);
210 // Forwards a directory status counter update to the frontend loop. Will not
211 // be called unless a call to EnableDirectoryTypeDebugInfoForwarding()
212 // explicitly requested that we start forwarding these events.
213 void HandleDirectoryStatusCountersUpdatedOnFrontendLoop(
214 syncer::ModelType type,
215 const syncer::StatusCounters& counters);
217 // Overwrites the kSyncInvalidationVersions preference with the most recent
218 // set of invalidation versions for each type.
219 void UpdateInvalidationVersions(
220 const std::map<syncer::ModelType, int64>& invalidation_versions);
222 sync_driver::SyncFrontend* frontend() {
223 return frontend_;
226 private:
227 friend class SyncBackendHostCore;
229 // Checks if we have received a notice to turn on experimental datatypes
230 // (via the nigori node) and informs the frontend if that is the case.
231 // Note: it is illegal to call this before the backend is initialized.
232 void AddExperimentalTypes();
234 // Handles backend initialization failure.
235 void HandleInitializationFailureOnFrontendLoop();
237 // Called from Core::OnSyncCycleCompleted to handle updating frontend
238 // thread components.
239 void HandleSyncCycleCompletedOnFrontendLoop(
240 const syncer::sessions::SyncSessionSnapshot& snapshot);
242 // Called when the syncer failed to perform a configuration and will
243 // eventually retry. FinishingConfigurationOnFrontendLoop(..) will be called
244 // on successful completion.
245 void RetryConfigurationOnFrontendLoop(const base::Closure& retry_callback);
247 // Helpers to persist a token that can be used to bootstrap sync encryption
248 // across browser restart to avoid requiring the user to re-enter their
249 // passphrase. |token| must be valid UTF-8 as we use the PrefService for
250 // storage.
251 void PersistEncryptionBootstrapToken(
252 const std::string& token,
253 syncer::BootstrapTokenType token_type);
255 // For convenience, checks if initialization state is INITIALIZED.
256 bool initialized() const { return initialized_; }
258 // Let the front end handle the actionable error event.
259 void HandleActionableErrorEventOnFrontendLoop(
260 const syncer::SyncProtocolError& sync_error);
262 // Handle a migration request.
263 void HandleMigrationRequestedOnFrontendLoop(const syncer::ModelTypeSet types);
265 // Checks if |passphrase| can be used to decrypt the cryptographer's pending
266 // keys that were cached during NotifyPassphraseRequired. Returns true if
267 // decryption was successful. Returns false otherwise. Must be called with a
268 // non-empty pending keys cache.
269 bool CheckPassphraseAgainstCachedPendingKeys(
270 const std::string& passphrase) const;
272 // Invoked when a passphrase is required to decrypt a set of Nigori keys,
273 // or for encrypting. |reason| denotes why the passphrase was required.
274 // |pending_keys| is a copy of the cryptographer's pending keys, that are
275 // cached by the frontend. If there are no pending keys, or if the passphrase
276 // required reason is REASON_ENCRYPTION, an empty EncryptedData object is
277 // passed.
278 void NotifyPassphraseRequired(syncer::PassphraseRequiredReason reason,
279 sync_pb::EncryptedData pending_keys);
281 // Invoked when the passphrase provided by the user has been accepted.
282 void NotifyPassphraseAccepted();
284 // Invoked when the set of encrypted types or the encrypt
285 // everything flag changes.
286 void NotifyEncryptedTypesChanged(
287 syncer::ModelTypeSet encrypted_types,
288 bool encrypt_everything);
290 // Invoked when sync finishes encrypting new datatypes.
291 void NotifyEncryptionComplete();
293 // Invoked when the passphrase state has changed. Caches the passphrase state
294 // for later use on the UI thread.
295 // If |type| is FROZEN_IMPLICIT_PASSPHRASE or CUSTOM_PASSPHRASE,
296 // |explicit_passphrase_time| is the time at which that passphrase was set
297 // (if available).
298 void HandlePassphraseTypeChangedOnFrontendLoop(
299 syncer::PassphraseType type,
300 base::Time explicit_passphrase_time);
302 void HandleLocalSetPassphraseEncryptionOnFrontendLoop(
303 const syncer::SyncEncryptionHandler::NigoriState& nigori_state);
305 // Dispatched to from OnConnectionStatusChange to handle updating
306 // frontend UI components.
307 void HandleConnectionStatusChangeOnFrontendLoop(
308 syncer::ConnectionStatus status);
310 // NotificationObserver implementation.
311 void Observe(int type,
312 const content::NotificationSource& source,
313 const content::NotificationDetails& details) override;
315 void ClearServerDataDoneOnFrontendLoop(
316 const syncer::SyncManager::ClearServerDataCallback& frontend_callback);
318 content::NotificationRegistrar notification_registrar_;
320 // A reference to the MessageLoop used to construct |this|, so we know how
321 // to safely talk back to the SyncFrontend.
322 base::MessageLoop* const frontend_loop_;
324 Profile* const profile_;
326 // Name used for debugging (set from profile_->GetDebugName()).
327 const std::string name_;
329 // Our core, which communicates directly to the syncapi. Use refptr instead
330 // of WeakHandle because |core_| is created on UI loop but released on
331 // sync loop.
332 scoped_refptr<SyncBackendHostCore> core_;
334 // A handle referencing the main interface for non-blocking sync types.
335 scoped_ptr<syncer_v2::SyncContextProxy> sync_context_proxy_;
337 bool initialized_;
339 const base::WeakPtr<sync_driver::SyncPrefs> sync_prefs_;
341 ExtensionsActivityMonitor extensions_activity_monitor_;
343 scoped_ptr<SyncBackendRegistrar> registrar_;
345 // The frontend which we serve (and are owned by).
346 sync_driver::SyncFrontend* frontend_;
348 // We cache the cryptographer's pending keys whenever NotifyPassphraseRequired
349 // is called. This way, before the UI calls SetDecryptionPassphrase on the
350 // syncer, it can avoid the overhead of an asynchronous decryption call and
351 // give the user immediate feedback about the passphrase entered by first
352 // trying to decrypt the cached pending keys on the UI thread. Note that
353 // SetDecryptionPassphrase can still fail after the cached pending keys are
354 // successfully decrypted if the pending keys have changed since the time they
355 // were cached.
356 sync_pb::EncryptedData cached_pending_keys_;
358 // The state of the passphrase required to decrypt the bag of encryption keys
359 // in the nigori node. Updated whenever a new nigori node arrives or the user
360 // manually changes their passphrase state. Cached so we can synchronously
361 // check it from the UI thread.
362 syncer::PassphraseType cached_passphrase_type_;
364 // If an explicit passphrase is in use, the time at which the passphrase was
365 // first set (if available).
366 base::Time cached_explicit_passphrase_time_;
368 // UI-thread cache of the last SyncSessionSnapshot received from syncapi.
369 syncer::sessions::SyncSessionSnapshot last_snapshot_;
371 invalidation::InvalidationService* invalidator_;
372 bool invalidation_handler_registered_;
374 base::WeakPtrFactory<SyncBackendHostImpl> weak_ptr_factory_;
376 DISALLOW_COPY_AND_ASSIGN(SyncBackendHostImpl);
379 } // namespace browser_sync
381 #endif // CHROME_BROWSER_SYNC_GLUE_SYNC_BACKEND_HOST_IMPL_H_