gcm_client.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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_CLIENT_H_
  5. #define COMPONENTS_GCM_DRIVER_GCM_CLIENT_H_
  6. #include <stdint.h>
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #include <vector>
  11. #include "base/memory/scoped_refptr.h"
  12. #include "base/time/time.h"
  13. #include "components/gcm_driver/common/gcm_message.h"
  14. #include "components/gcm_driver/gcm_activity.h"
  15. #include "components/gcm_driver/registration_info.h"
  16. #include "google_apis/gaia/core_account_id.h"
  17. #include "mojo/public/cpp/bindings/pending_receiver.h"
  18. #include "services/network/public/mojom/proxy_resolving_socket.mojom-forward.h"
  19. namespace base {
  20. class FilePath;
  21. class RetainingOneShotTimer;
  22. class SequencedTaskRunner;
  23. } // namespace base
  24. namespace net {
  25. class IPEndPoint;
  26. } // namespace net
  27. namespace network {
  28. class NetworkConnectionTracker;
  29. class SharedURLLoaderFactory;
  30. } // namespace network
  31. namespace gcm {
  32. struct AccountMapping;
  33. class Encryptor;
  34. enum class GCMDecryptionResult;
  35. // Interface that encapsulates the network communications with the Google Cloud
  36. // Messaging server. This interface is not supposed to be thread-safe.
  37. class GCMClient {
  38. public:
  39. // Controls how GCM is being started. At first, GCMClient will be initialized
  40. // and GCM store will be loaded. Then GCM connection may or may not be
  41. // initiated depending on this enum value.
  42. enum StartMode {
  43. // GCM should be started only when it is being actually used. If no
  44. // registration record is found, GCM will not kick off.
  45. DELAYED_START,
  46. // GCM should be started immediately.
  47. IMMEDIATE_START
  48. };
  49. // Used for UMA. Can add enum values, but never renumber or delete and reuse.
  50. enum Result : uint8_t {
  51. // Successful operation.
  52. SUCCESS,
  53. // Invalid parameter.
  54. INVALID_PARAMETER,
  55. // GCM is disabled.
  56. GCM_DISABLED,
  57. // Previous asynchronous operation is still pending to finish. Certain
  58. // operation, like register, is only allowed one at a time.
  59. ASYNC_OPERATION_PENDING,
  60. // Network socket error.
  61. NETWORK_ERROR,
  62. // Problem at the server.
  63. SERVER_ERROR,
  64. // Exceeded the specified TTL during message sending.
  65. TTL_EXCEEDED,
  66. // Other errors.
  67. UNKNOWN_ERROR,
  68. // Used for UMA. Keep kMaxValue up to date and sync with histograms.xml.
  69. kMaxValue = UNKNOWN_ERROR
  70. };
  71. enum ChromePlatform {
  72. PLATFORM_WIN,
  73. PLATFORM_MAC,
  74. PLATFORM_LINUX,
  75. PLATFORM_CROS,
  76. PLATFORM_IOS,
  77. PLATFORM_ANDROID,
  78. PLATFORM_UNSPECIFIED
  79. };
  80. enum ChromeChannel {
  81. CHANNEL_STABLE,
  82. CHANNEL_BETA,
  83. CHANNEL_DEV,
  84. CHANNEL_CANARY,
  85. CHANNEL_UNKNOWN
  86. };
  87. struct ChromeBuildInfo {
  88. ChromeBuildInfo();
  89. ~ChromeBuildInfo();
  90. ChromePlatform platform;
  91. ChromeChannel channel;
  92. std::string version;
  93. std::string product_category_for_subtypes;
  94. };
  95. // Detailed information of the Send Error event.
  96. struct SendErrorDetails {
  97. SendErrorDetails();
  98. SendErrorDetails(const SendErrorDetails& other);
  99. ~SendErrorDetails();
  100. std::string message_id;
  101. MessageData additional_data;
  102. Result result;
  103. };
  104. // Internal states and activity statistics of a GCM client.
  105. struct GCMStatistics {
  106. public:
  107. GCMStatistics();
  108. GCMStatistics(const GCMStatistics& other);
  109. ~GCMStatistics();
  110. bool is_recording;
  111. bool gcm_client_created;
  112. std::string gcm_client_state;
  113. bool connection_client_created;
  114. std::string connection_state;
  115. base::Time last_checkin;
  116. base::Time next_checkin;
  117. uint64_t android_id;
  118. uint64_t android_secret;
  119. std::vector<std::string> registered_app_ids;
  120. int send_queue_size;
  121. int resend_queue_size;
  122. RecordedActivities recorded_activities;
  123. };
  124. // Information about account.
  125. struct AccountTokenInfo {
  126. CoreAccountId account_id;
  127. std::string email;
  128. std::string access_token;
  129. };
  130. // A delegate interface that allows the GCMClient instance to interact with
  131. // its caller, i.e. notifying asynchronous event.
  132. class Delegate {
  133. public:
  134. // Called when the registration completed successfully or an error occurs.
  135. // |registration_info|: the specific information required for the
  136. // registration.
  137. // |registration_id|: non-empty if the registration completed successfully.
  138. // |result|: the type of the error if an error occured, success otherwise.
  139. virtual void OnRegisterFinished(
  140. scoped_refptr<RegistrationInfo> registration_info,
  141. const std::string& registration_id,
  142. Result result) = 0;
  143. // Called when the unregistration completed.
  144. // |registration_info|: the specific information required for the
  145. // registration.
  146. // |result|: result of the unregistration.
  147. virtual void OnUnregisterFinished(
  148. scoped_refptr<RegistrationInfo> registration_info,
  149. GCMClient::Result result) = 0;
  150. // Called when the message is scheduled to send successfully or an error
  151. // occurs.
  152. // |app_id|: application ID.
  153. // |message_id|: ID of the message being sent.
  154. // |result|: the type of the error if an error occured, success otherwise.
  155. virtual void OnSendFinished(const std::string& app_id,
  156. const std::string& message_id,
  157. Result result) = 0;
  158. // Called when a message has been received.
  159. // |app_id|: application ID.
  160. // |message|: message received.
  161. virtual void OnMessageReceived(const std::string& app_id,
  162. const IncomingMessage& message) = 0;
  163. // Called when some messages have been deleted from the server.
  164. // |app_id|: application ID.
  165. virtual void OnMessagesDeleted(const std::string& app_id) = 0;
  166. // Called when a message failed to send to the server.
  167. // |app_id|: application ID.
  168. // |send_error_detials|: Details of the send error event, like mesasge ID.
  169. virtual void OnMessageSendError(
  170. const std::string& app_id,
  171. const SendErrorDetails& send_error_details) = 0;
  172. // Called when a message was acknowledged by the GCM server.
  173. // |app_id|: application ID.
  174. // |message_id|: ID of the acknowledged message.
  175. virtual void OnSendAcknowledged(const std::string& app_id,
  176. const std::string& message_id) = 0;
  177. // Called when the GCM becomes ready. To get to this state, GCMClient
  178. // finished loading from the GCM store and retrieved the device check-in
  179. // from the server if it hadn't yet.
  180. // |account_mappings|: a persisted list of accounts mapped to this GCM
  181. // client.
  182. // |last_token_fetch_time|: time of a last successful token fetch.
  183. virtual void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
  184. const base::Time& last_token_fetch_time) = 0;
  185. // Called when activities are being recorded and a new activity has just
  186. // been recorded.
  187. virtual void OnActivityRecorded() = 0;
  188. // Called when a new connection is established and a successful handshake
  189. // has been performed.
  190. virtual void OnConnected(const net::IPEndPoint& ip_endpoint) = 0;
  191. // Called when the connection is interrupted.
  192. virtual void OnDisconnected() = 0;
  193. // Called when the GCM store is reset (e.g. due to corruption), which
  194. // changes the device ID, invalidating all prior registrations.
  195. virtual void OnStoreReset() = 0;
  196. };
  197. GCMClient();
  198. virtual ~GCMClient();
  199. // Begins initialization of the GCM Client. This will not trigger a
  200. // connection. Must be called on |io_task_runner|.
  201. // |chrome_build_info|: chrome info, i.e., version, channel and etc.
  202. // |store_path|: path to the GCM store.
  203. // |remove_account_mappings_with_email_key|: Whether account mappings having
  204. // email as account key should be removed while loading. Required
  205. // during the migration of account identifier from email to Gaia ID.
  206. // |blocking_task_runner|: for running blocking file tasks.
  207. // |io_task_runner|: for running IO tasks. When provided, it could be a
  208. // wrapper on top of base::ThreadTaskRunnerHandle::Get() to provide power
  209. // management featueres so that a delayed task posted to it can wake the
  210. // system up from sleep to perform the task.
  211. // |get_socket_factory_callback|: a callback that can accept a receiver for a
  212. // network::mojom::ProxyResolvingSocketFactory. It needs to be safe to
  213. // run on any thread.
  214. // |delegate|: the delegate whose methods will be called asynchronously in
  215. // response to events and messages.
  216. virtual void Initialize(
  217. const ChromeBuildInfo& chrome_build_info,
  218. const base::FilePath& store_path,
  219. bool remove_account_mappings_with_email_key,
  220. const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner,
  221. scoped_refptr<base::SequencedTaskRunner> io_task_runner,
  222. base::RepeatingCallback<void(
  223. mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>)>
  224. get_socket_factory_callback,
  225. const scoped_refptr<network::SharedURLLoaderFactory>& url_loader_factory,
  226. network::NetworkConnectionTracker* network_connection_tracker_,
  227. std::unique_ptr<Encryptor> encryptor,
  228. Delegate* delegate) = 0;
  229. // This will initiate the GCM connection only if |start_mode| means to start
  230. // the GCM immediately or the GCM registration records are found in the store.
  231. // Note that it is OK to call Start multiple times and the implementation
  232. // should handle it gracefully.
  233. virtual void Start(StartMode start_mode) = 0;
  234. // Stops using the GCM service. This will not erase the persisted data.
  235. virtual void Stop() = 0;
  236. // Registers with the server to access the provided service.
  237. // Delegate::OnRegisterFinished will be called asynchronously upon completion.
  238. // |registration_info|: the specific information required for the
  239. // registration. For GCM, it will contain app id and
  240. // sender IDs. For InstanceID, it will contain app_id,
  241. // authorized entity and scope.
  242. virtual void Register(scoped_refptr<RegistrationInfo> registration_info) = 0;
  243. // Checks that the provided |registration_id| (aka token for Instance ID
  244. // registrations) matches the stored registration info. Also checks sender IDs
  245. // match for GCM registrations.
  246. virtual bool ValidateRegistration(
  247. scoped_refptr<RegistrationInfo> registration_info,
  248. const std::string& registration_id) = 0;
  249. // Unregisters from the server to stop accessing the provided service.
  250. // Delegate::OnUnregisterFinished will be called asynchronously upon
  251. // completion.
  252. // |registration_info|: the specific information required for the
  253. // registration. For GCM, it will contain app id (sender
  254. // IDs can be ingored). For InstanceID, it will contain
  255. // app id, authorized entity and scope.
  256. virtual void Unregister(
  257. scoped_refptr<RegistrationInfo> registration_info) = 0;
  258. // Sends a message to a given receiver. Delegate::OnSendFinished will be
  259. // called asynchronously upon completion.
  260. // |app_id|: application ID.
  261. // |receiver_id|: registration ID of the receiver party.
  262. // |message|: message to be sent.
  263. virtual void Send(const std::string& app_id,
  264. const std::string& receiver_id,
  265. const OutgoingMessage& message) = 0;
  266. // Records a decryption failure due to |result| for the |app_id|.
  267. virtual void RecordDecryptionFailure(const std::string& app_id,
  268. GCMDecryptionResult result) = 0;
  269. // Enables or disables internal activity recording.
  270. virtual void SetRecording(bool recording) = 0;
  271. // Clear all recorded GCM activity logs.
  272. virtual void ClearActivityLogs() = 0;
  273. // Gets internal states and statistics.
  274. virtual GCMStatistics GetStatistics() const = 0;
  275. // Sets a list of accounts with OAuth2 tokens for the next checkin.
  276. // |account_tokens|: list of email addresses, account IDs and OAuth2 access
  277. // tokens.
  278. virtual void SetAccountTokens(
  279. const std::vector<AccountTokenInfo>& account_tokens) = 0;
  280. // Persists the |account_mapping| in the store.
  281. virtual void UpdateAccountMapping(const AccountMapping& account_mapping) = 0;
  282. // Removes the account mapping related to |account_id| from the persistent
  283. // store.
  284. virtual void RemoveAccountMapping(const CoreAccountId& account_id) = 0;
  285. // Sets last token fetch time in persistent store.
  286. virtual void SetLastTokenFetchTime(const base::Time& time) = 0;
  287. // Updates the timer used by the HeartbeatManager for sending heartbeats.
  288. virtual void UpdateHeartbeatTimer(
  289. std::unique_ptr<base::RetainingOneShotTimer> timer) = 0;
  290. // Adds the Instance ID data for a specific app to the persistent store.
  291. virtual void AddInstanceIDData(const std::string& app_id,
  292. const std::string& instance_id,
  293. const std::string& extra_data) = 0;
  294. // Removes the Instance ID data for a specific app from the persistent store.
  295. virtual void RemoveInstanceIDData(const std::string& app_id) = 0;
  296. // Retrieves the Instance ID data for a specific app from the persistent
  297. // store.
  298. virtual void GetInstanceIDData(const std::string& app_id,
  299. std::string* instance_id,
  300. std::string* extra_data) = 0;
  301. // Gets and sets custom heartbeat interval for the MCS connection.
  302. // |scope| is used to identify the component that requests a custom interval
  303. // to be set, and allows that component to later revoke the setting. It should
  304. // be unique.
  305. virtual void AddHeartbeatInterval(const std::string& scope,
  306. int interval_ms) = 0;
  307. virtual void RemoveHeartbeatInterval(const std::string& scope) = 0;
  308. };
  309. } // namespace gcm
  310. #endif // COMPONENTS_GCM_DRIVER_GCM_CLIENT_H_