gcm_driver.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Copyright 2014 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. #ifndef COMPONENTS_GCM_DRIVER_GCM_DRIVER_H_
  5. #define COMPONENTS_GCM_DRIVER_GCM_DRIVER_H_
  6. #include <map>
  7. #include <string>
  8. #include <vector>
  9. #include "base/callback.h"
  10. #include "base/memory/ref_counted.h"
  11. #include "base/memory/weak_ptr.h"
  12. #include "base/threading/thread_checker.h"
  13. #include "base/time/time.h"
  14. #include "components/gcm_driver/common/gcm_message.h"
  15. #include "components/gcm_driver/crypto/gcm_encryption_provider.h"
  16. #include "components/gcm_driver/gcm_client.h"
  17. namespace base {
  18. class FilePath;
  19. class SequencedTaskRunner;
  20. } // namespace base
  21. namespace gcm {
  22. class GCMAppHandler;
  23. class GCMConnectionObserver;
  24. enum class GCMDecryptionResult;
  25. enum class GCMEncryptionResult;
  26. struct AccountMapping;
  27. // Provides the InstanceID support via GCMDriver.
  28. class InstanceIDHandler {
  29. public:
  30. using GetTokenCallback = base::OnceCallback<void(const std::string& token,
  31. GCMClient::Result result)>;
  32. using ValidateTokenCallback = base::OnceCallback<void(bool is_valid)>;
  33. using DeleteTokenCallback =
  34. base::OnceCallback<void(GCMClient::Result result)>;
  35. using GetInstanceIDDataCallback =
  36. base::OnceCallback<void(const std::string& instance_id,
  37. const std::string& extra_data)>;
  38. InstanceIDHandler();
  39. InstanceIDHandler(const InstanceIDHandler&) = delete;
  40. InstanceIDHandler& operator=(const InstanceIDHandler&) = delete;
  41. virtual ~InstanceIDHandler();
  42. // Token service.
  43. virtual void GetToken(const std::string& app_id,
  44. const std::string& authorized_entity,
  45. const std::string& scope,
  46. base::TimeDelta time_to_live,
  47. GetTokenCallback callback) = 0;
  48. virtual void ValidateToken(const std::string& app_id,
  49. const std::string& authorized_entity,
  50. const std::string& scope,
  51. const std::string& token,
  52. ValidateTokenCallback callback) = 0;
  53. virtual void DeleteToken(const std::string& app_id,
  54. const std::string& authorized_entity,
  55. const std::string& scope,
  56. DeleteTokenCallback callback) = 0;
  57. void DeleteAllTokensForApp(const std::string& app_id,
  58. DeleteTokenCallback callback);
  59. // Persistence support.
  60. virtual void AddInstanceIDData(const std::string& app_id,
  61. const std::string& instance_id,
  62. const std::string& extra_data) = 0;
  63. virtual void RemoveInstanceIDData(const std::string& app_id) = 0;
  64. virtual void GetInstanceIDData(const std::string& app_id,
  65. GetInstanceIDDataCallback callback) = 0;
  66. };
  67. // Bridge between GCM users in Chrome and the platform-specific implementation.
  68. // Obtain instances of this object by using |GCMProfileServiceFactory|.
  69. class GCMDriver {
  70. public:
  71. // Max number of sender IDs that can be passed to |Register| on desktop.
  72. constexpr static size_t kMaxSenders = 100;
  73. using GCMAppHandlerMap = std::map<std::string, GCMAppHandler*>;
  74. using RegisterCallback =
  75. base::OnceCallback<void(const std::string& registration_id,
  76. GCMClient::Result result)>;
  77. using ValidateRegistrationCallback = base::OnceCallback<void(bool is_valid)>;
  78. using UnregisterCallback = base::OnceCallback<void(GCMClient::Result result)>;
  79. using SendCallback = base::OnceCallback<void(const std::string& message_id,
  80. GCMClient::Result result)>;
  81. using GetEncryptionInfoCallback =
  82. base::OnceCallback<void(std::string p256dh, std::string auth_secret)>;
  83. using EncryptMessageCallback =
  84. base::OnceCallback<void(GCMEncryptionResult result, std::string message)>;
  85. using DecryptMessageCallback =
  86. base::OnceCallback<void(GCMDecryptionResult result, std::string message)>;
  87. using GetGCMStatisticsCallback =
  88. base::OnceCallback<void(const GCMClient::GCMStatistics& stats)>;
  89. using GCMStatisticsRecordingCallback =
  90. base::RepeatingCallback<void(const GCMClient::GCMStatistics& stats)>;
  91. // Enumeration to be used with GetGCMStatistics() for indicating whether the
  92. // existing logs should be cleared or kept.
  93. enum ClearActivityLogs { CLEAR_LOGS, KEEP_LOGS };
  94. GCMDriver(
  95. const base::FilePath& store_path,
  96. const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner);
  97. GCMDriver(const GCMDriver&) = delete;
  98. GCMDriver& operator=(const GCMDriver&) = delete;
  99. virtual ~GCMDriver();
  100. // Registers |sender_ids| for an app. *Use |InstanceID| instead in new code.*
  101. //
  102. // A registration ID will be returned by the GCM server. On Android, only a
  103. // single sender ID is supported, but instead multiple simultaneous
  104. // registrations are allowed.
  105. // |app_id|: application ID.
  106. // |sender_ids|: list of IDs of the servers allowed to send messages to the
  107. // application. The IDs are assigned by the Google API Console.
  108. // Max number of IDs is 1 on Android, |kMaxSenders| on desktop.
  109. // |callback|: to be called once the asynchronous operation is done.
  110. void Register(const std::string& app_id,
  111. const std::vector<std::string>& sender_ids,
  112. RegisterCallback callback);
  113. // Checks that the provided |sender_ids| and |registration_id| matches the
  114. // stored registration info for |app_id|.
  115. virtual void ValidateRegistration(const std::string& app_id,
  116. const std::vector<std::string>& sender_ids,
  117. const std::string& registration_id,
  118. ValidateRegistrationCallback callback) = 0;
  119. // Unregisters all sender_ids for an app. Only works on non-Android. Will also
  120. // remove any encryption keys associated with the |app_id|.
  121. // |app_id|: application ID.
  122. // |callback|: to be called once the asynchronous operation is done.
  123. void Unregister(const std::string& app_id, UnregisterCallback callback);
  124. // Unregisters an (app_id, sender_id) pair from using GCM. Only works on
  125. // Android. Will also remove any encryption keys associated with the |app_id|.
  126. // TODO(jianli): Switch to using GCM's unsubscribe API.
  127. // |app_id|: application ID.
  128. // |sender_id|: the sender ID that was passed when registering.
  129. // |callback|: to be called once the asynchronous operation is done.
  130. void UnregisterWithSenderId(const std::string& app_id,
  131. const std::string& sender_id,
  132. UnregisterCallback callback);
  133. // Sends a message to a given receiver.
  134. // |app_id|: application ID.
  135. // |receiver_id|: registration ID of the receiver party.
  136. // |message|: message to be sent.
  137. // |callback|: to be called once the asynchronous operation is done.
  138. void Send(const std::string& app_id,
  139. const std::string& receiver_id,
  140. const OutgoingMessage& message,
  141. SendCallback callback);
  142. // Get the public encryption key and the authentication secret associated with
  143. // |app_id|. If none have been associated with |app_id| yet, they will be
  144. // created. The |callback| will be invoked when it is available. Only use with
  145. // GCM registrations; use InstanceID::GetEncryptionInfo for InstanceID tokens.
  146. virtual void GetEncryptionInfo(const std::string& app_id,
  147. GetEncryptionInfoCallback callback);
  148. // Attempts to encrypt the |message| using draft-ietf-webpush-encryption-08
  149. // scheme using keys from internal key store. Either GetEncryptionInfo or
  150. // InstanceID::GetEncryptionInfo must be called once for keys to be available.
  151. // |callback| will be called asynchronously when |message| has been encrypted.
  152. // A dispatchable message will be used in case of success, an empty message in
  153. // case of failure.
  154. virtual void EncryptMessage(const std::string& app_id,
  155. const std::string& authorized_entity,
  156. const std::string& p256dh,
  157. const std::string& auth_secret,
  158. const std::string& message,
  159. EncryptMessageCallback callback);
  160. // Attempts to decrypt the |message|using draft-ietf-webpush-encryption-08
  161. // scheme using keys from internal key store. Either GetEncryptionInfo or
  162. // InstanceID::GetEncryptionInfo must be called once for keys to be available.
  163. // |callback| will be called asynchronously when |message| has been decrypted.
  164. // A dispatchable message will be used in case of success, an empty message in
  165. // case of failure.
  166. // TODO(crbug/1045907): Decouple this from GCMDriver.
  167. virtual void DecryptMessage(const std::string& app_id,
  168. const std::string& authorized_entity,
  169. const std::string& message,
  170. DecryptMessageCallback callback);
  171. const GCMAppHandlerMap& app_handlers() const { return app_handlers_; }
  172. // This method must be called before destroying the GCMDriver. Once it has
  173. // been called, no other GCMDriver methods may be used.
  174. virtual void Shutdown();
  175. // Called when the user signs in to or out of a GAIA account.
  176. virtual void OnSignedIn() = 0;
  177. virtual void OnSignedOut() = 0;
  178. // Adds a handler for a given app.
  179. virtual void AddAppHandler(const std::string& app_id, GCMAppHandler* handler);
  180. // Remove the handler for a given app.
  181. virtual void RemoveAppHandler(const std::string& app_id);
  182. // Returns the handler for the given app. May return a nullptr when no handler
  183. // could be found for the |app_id|.
  184. GCMAppHandler* GetAppHandler(const std::string& app_id);
  185. // Adds a connection state observer.
  186. virtual void AddConnectionObserver(GCMConnectionObserver* observer) = 0;
  187. // Removes a connection state observer.
  188. virtual void RemoveConnectionObserver(GCMConnectionObserver* observer) = 0;
  189. // For testing purpose. Always NULL on Android.
  190. virtual GCMClient* GetGCMClientForTesting() const = 0;
  191. // Returns true if the service was started.
  192. virtual bool IsStarted() const = 0;
  193. // Returns true if the gcm client has an open and active connection.
  194. virtual bool IsConnected() const = 0;
  195. // Get GCM client internal states and statistics. The activity logs will be
  196. // cleared before returning the stats when |clear_logs| is set to CLEAR_LOGS.
  197. virtual void GetGCMStatistics(GetGCMStatisticsCallback callback,
  198. ClearActivityLogs clear_logs) = 0;
  199. // Enables/disables GCM activity recording, and then returns the stats.
  200. // |callback| will be called for new activity.
  201. virtual void SetGCMRecording(const GCMStatisticsRecordingCallback& callback,
  202. bool recording) = 0;
  203. // sets a list of signed in accounts with OAuth2 access tokens, when GCMDriver
  204. // works in context of a signed in entity (e.g. browser profile where user is
  205. // signed into sync).
  206. // |account_tokens|: list of email addresses, account IDs and OAuth2 access
  207. // tokens.
  208. virtual void SetAccountTokens(
  209. const std::vector<GCMClient::AccountTokenInfo>& account_tokens) = 0;
  210. // Updates the |account_mapping| information in persistent store.
  211. virtual void UpdateAccountMapping(const AccountMapping& account_mapping) = 0;
  212. // Removes the account mapping information reated to |account_id| from
  213. // persistent store.
  214. virtual void RemoveAccountMapping(const CoreAccountId& account_id) = 0;
  215. // Getter and setter of last token fetch time.
  216. virtual base::Time GetLastTokenFetchTime() = 0;
  217. virtual void SetLastTokenFetchTime(const base::Time& time) = 0;
  218. // These methods must only be used by the InstanceID system.
  219. // The InstanceIDHandler provides an implementation for the InstanceID system.
  220. virtual InstanceIDHandler* GetInstanceIDHandlerInternal() = 0;
  221. // Allows the InstanceID system to integrate with GCM encryption storage.
  222. virtual GCMEncryptionProvider* GetEncryptionProviderInternal();
  223. // Adds or removes a custom client requested heartbeat interval. If multiple
  224. // components set that setting, the lowest setting will be used. If the
  225. // setting is outside of GetMax/MinClientHeartbeatIntervalMs() it will be
  226. // ignored. If a new setting is less than the currently used, the connection
  227. // will be reset with the new heartbeat. Client that no longer require
  228. // aggressive heartbeats, should remove their requested interval. Heartbeats
  229. // set this way survive connection/Chrome restart.
  230. //
  231. // GCM Driver can decide to postpone the action until Client is properly
  232. // initialized, hence this setting can be called at any time.
  233. //
  234. // Server can overwrite the setting to a different value.
  235. //
  236. // |scope| is used to identify the component that requests a custom interval
  237. // to be set, and allows that component to later revoke the setting.
  238. // |interval_ms| should be between 2 minues and 15 minues (28 minues on
  239. // cellular networks). For details check
  240. // GetMin/MaxClientHeartbeatItnervalMs() in HeartbeatManager.
  241. virtual void AddHeartbeatInterval(const std::string& scope,
  242. int interval_ms) = 0;
  243. virtual void RemoveHeartbeatInterval(const std::string& scope) = 0;
  244. protected:
  245. // Ensures that the GCM service starts (if necessary conditions are met).
  246. virtual GCMClient::Result EnsureStarted(GCMClient::StartMode start_mode) = 0;
  247. // Platform-specific implementation of Register.
  248. virtual void RegisterImpl(const std::string& app_id,
  249. const std::vector<std::string>& sender_ids) = 0;
  250. // Platform-specific implementation of Unregister.
  251. virtual void UnregisterImpl(const std::string& app_id) = 0;
  252. // Platform-specific implementation of UnregisterWithSenderId.
  253. virtual void UnregisterWithSenderIdImpl(const std::string& app_id,
  254. const std::string& sender_id);
  255. // Platform-specific implementation of Send.
  256. virtual void SendImpl(const std::string& app_id,
  257. const std::string& receiver_id,
  258. const OutgoingMessage& message) = 0;
  259. // Platform-specific implementation of recording message decryption failures.
  260. virtual void RecordDecryptionFailure(const std::string& app_id,
  261. GCMDecryptionResult result) = 0;
  262. // Runs the Register callback.
  263. void RegisterFinished(const std::string& app_id,
  264. const std::string& registration_id,
  265. GCMClient::Result result);
  266. // To be called when a registration for |app_id| has been unregistered, having
  267. // |result| as the result of the unregistration. Will remove any encryption
  268. // information associated with the |app_id| and then calls UnregisterFinished.
  269. void RemoveEncryptionInfoAfterUnregister(const std::string& app_id,
  270. GCMClient::Result result);
  271. // Runs the Unregister callback.
  272. void UnregisterFinished(const std::string& app_id, GCMClient::Result result);
  273. // Runs the Send callback.
  274. void SendFinished(const std::string& app_id,
  275. const std::string& message_id,
  276. GCMClient::Result result);
  277. bool HasRegisterCallback(const std::string& app_id);
  278. void ClearCallbacks();
  279. // Dispatches the OnMessage event to the app handler associated with |app_id|.
  280. // If |message| has been encrypted, it will be decrypted asynchronously and
  281. // dispatched when the decryption operation was successful. Otherwise, the
  282. // |message| will be dispatched immediately to the handler for |app_id|.
  283. void DispatchMessage(const std::string& app_id,
  284. const IncomingMessage& message);
  285. private:
  286. // Common code shared by Unregister and UnregisterWithSenderId.
  287. void UnregisterInternal(const std::string& app_id,
  288. const std::string* sender_id,
  289. UnregisterCallback callback);
  290. // Dispatches the OnMessage event to the app handler associated with |app_id|
  291. // if |result| indicates that it is safe to do so, or will report a decryption
  292. // failure for the |app_id| otherwise.
  293. void DispatchMessageInternal(const std::string& app_id,
  294. GCMDecryptionResult result,
  295. IncomingMessage message);
  296. // Called after unregistration completes in order to trigger the pending
  297. // registration.
  298. void RegisterAfterUnregister(
  299. const std::string& app_id,
  300. const std::vector<std::string>& normalized_sender_ids,
  301. UnregisterCallback unregister_callback,
  302. GCMClient::Result result);
  303. void OnMessageEncrypted(EncryptMessageCallback callback,
  304. GCMEncryptionResult result,
  305. std::string message);
  306. void OnMessageDecrypted(DecryptMessageCallback callback,
  307. GCMDecryptionResult result,
  308. IncomingMessage message);
  309. // Callback map (from app_id to callback) for Register.
  310. std::map<std::string, RegisterCallback> register_callbacks_;
  311. // Callback map (from app_id to callback) for Unregister.
  312. std::map<std::string, UnregisterCallback> unregister_callbacks_;
  313. // Callback map (from <app_id, message_id> to callback) for Send.
  314. std::map<std::pair<std::string, std::string>, SendCallback> send_callbacks_;
  315. // The encryption provider, used for key management and decryption of
  316. // encrypted, incoming messages.
  317. GCMEncryptionProvider encryption_provider_;
  318. // App handler map (from app_id to handler pointer). The handler is not owned.
  319. GCMAppHandlerMap app_handlers_;
  320. base::WeakPtrFactory<GCMDriver> weak_ptr_factory_{this};
  321. };
  322. } // namespace gcm
  323. #endif // COMPONENTS_GCM_DRIVER_GCM_DRIVER_H_