FIRMessagingCheckinService.m 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinService.h"
  17. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  18. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  21. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  22. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthService.h"
  23. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinPreferences.h"
  24. static NSString *const kDeviceCheckinURL = @"https://device-provisioning.googleapis.com/checkin";
  25. // keys in Checkin preferences
  26. NSString *const kFIRMessagingDeviceAuthIdKey = @"GMSInstanceIDDeviceAuthIdKey";
  27. NSString *const kFIRMessagingSecretTokenKey = @"GMSInstanceIDSecretTokenKey";
  28. NSString *const kFIRMessagingDigestStringKey = @"GMSInstanceIDDigestKey";
  29. NSString *const kFIRMessagingLastCheckinTimeKey = @"GMSInstanceIDLastCheckinTimestampKey";
  30. NSString *const kFIRMessagingVersionInfoStringKey = @"GMSInstanceIDVersionInfo";
  31. NSString *const kFIRMessagingGServicesDictionaryKey = @"GMSInstanceIDGServicesData";
  32. NSString *const kFIRMessagingDeviceDataVersionKey = @"GMSInstanceIDDeviceDataVersion";
  33. static NSUInteger const kCheckinType = 2; // DeviceType IOS in l/w/a/_checkin.proto
  34. static NSUInteger const kCheckinVersion = 2;
  35. static NSUInteger const kFragment = 0;
  36. @interface FIRMessagingCheckinService ()
  37. @property(nonatomic, readwrite, strong) NSURLSession *session;
  38. @end
  39. @implementation FIRMessagingCheckinService
  40. - (instancetype)init {
  41. self = [super init];
  42. if (self) {
  43. // Create an URLSession once, even though checkin should happen about once a day
  44. NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
  45. config.timeoutIntervalForResource = 60.0f; // 1 minute
  46. config.allowsCellularAccess = YES;
  47. self.session = [NSURLSession sessionWithConfiguration:config];
  48. self.session.sessionDescription = @"com.google.iid-checkin";
  49. }
  50. return self;
  51. }
  52. - (void)dealloc {
  53. [self.session invalidateAndCancel];
  54. }
  55. - (void)checkinWithExistingCheckin:(FIRMessagingCheckinPreferences *)existingCheckin
  56. completion:(FIRMessagingDeviceCheckinCompletion)completion {
  57. if (self.session == nil) {
  58. FIRMessagingLoggerError(kFIRMessagingMessageCodeService005,
  59. @"Inconsistent state: NSURLSession has been invalidated");
  60. NSError *error =
  61. [NSError messagingErrorWithCode:kFIRMessagingErrorCodeRegistrarFailedToCheckIn
  62. failureReason:@"Failed to checkin. NSURLSession is invalid."];
  63. if (completion) {
  64. completion(nil, error);
  65. }
  66. return;
  67. }
  68. NSURL *url = [NSURL URLWithString:kDeviceCheckinURL];
  69. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  70. [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  71. NSDictionary *checkinParameters = [self checkinParametersWithExistingCheckin:existingCheckin];
  72. NSData *checkinData = [NSJSONSerialization dataWithJSONObject:checkinParameters
  73. options:0
  74. error:nil];
  75. request.HTTPMethod = @"POST";
  76. request.HTTPBody = checkinData;
  77. void (^handler)(NSData *, NSURLResponse *, NSError *) =
  78. ^(NSData *data, NSURLResponse *response, NSError *error) {
  79. if (error) {
  80. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService000,
  81. @"Device checkin HTTP fetch error. Error Code: %ld",
  82. (long)error.code);
  83. if (completion) {
  84. completion(nil, error);
  85. }
  86. return;
  87. }
  88. NSError *serializationError = nil;
  89. NSDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data
  90. options:0
  91. error:&serializationError];
  92. if (serializationError) {
  93. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService001,
  94. @"Error serializing json object. Error Code: %ld",
  95. (long)serializationError.code);
  96. if (completion) {
  97. completion(nil, serializationError);
  98. }
  99. return;
  100. }
  101. NSString *deviceAuthID = [dataResponse[@"android_id"] stringValue];
  102. NSString *secretToken = [dataResponse[@"security_token"] stringValue];
  103. if ([deviceAuthID length] == 0) {
  104. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  105. failureReason:@"Invalid device auth ID."];
  106. if (completion) {
  107. completion(nil, error);
  108. }
  109. return;
  110. }
  111. int64_t lastCheckinTimestampMillis = [dataResponse[@"time_msec"] longLongValue];
  112. int64_t currentTimestampMillis = FIRMessagingCurrentTimestampInMilliseconds();
  113. // Somehow the server clock gets out of sync with the device clock.
  114. // Reset the last checkin timestamp in case this happens.
  115. if (lastCheckinTimestampMillis > currentTimestampMillis) {
  116. FIRMessagingLoggerDebug(
  117. kFIRMessagingMessageCodeService002, @"Invalid last checkin timestamp %@ in future.",
  118. [NSDate dateWithTimeIntervalSince1970:lastCheckinTimestampMillis / 1000.0]);
  119. lastCheckinTimestampMillis = currentTimestampMillis;
  120. }
  121. NSString *deviceDataVersionInfo = dataResponse[@"device_data_version_info"] ?: @"";
  122. NSString *digest = dataResponse[@"digest"] ?: @"";
  123. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService003,
  124. @"Checkin successful with authId: %@, "
  125. @"digest: %@, "
  126. @"lastCheckinTimestamp: %lld",
  127. deviceAuthID, digest, lastCheckinTimestampMillis);
  128. NSString *versionInfo = dataResponse[@"version_info"] ?: @"";
  129. NSMutableDictionary *gservicesData = [NSMutableDictionary dictionary];
  130. // Read gServices data.
  131. NSArray *flatSettings = dataResponse[@"setting"];
  132. for (NSDictionary *dict in flatSettings) {
  133. if (dict[@"name"] && dict[@"value"]) {
  134. gservicesData[dict[@"name"]] = dict[@"value"];
  135. } else {
  136. FIRMessagingLoggerDebug(kFIRMessagingInvalidSettingResponse,
  137. @"Invalid setting in checkin response: (%@: %@)", dict[@"name"],
  138. dict[@"value"]);
  139. }
  140. }
  141. FIRMessagingCheckinPreferences *checkinPreferences =
  142. [[FIRMessagingCheckinPreferences alloc] initWithDeviceID:deviceAuthID
  143. secretToken:secretToken];
  144. NSDictionary *preferences = @{
  145. kFIRMessagingDigestStringKey : digest,
  146. kFIRMessagingVersionInfoStringKey : versionInfo,
  147. kFIRMessagingLastCheckinTimeKey : @(lastCheckinTimestampMillis),
  148. kFIRMessagingGServicesDictionaryKey : gservicesData,
  149. kFIRMessagingDeviceDataVersionKey : deviceDataVersionInfo,
  150. };
  151. [checkinPreferences updateWithCheckinPlistContents:preferences];
  152. if (completion) {
  153. completion(checkinPreferences, nil);
  154. }
  155. };
  156. NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:handler];
  157. [task resume];
  158. }
  159. - (void)stopFetching {
  160. [self.session invalidateAndCancel];
  161. // The session cannot be reused after invalidation. Dispose it to prevent accident reusing.
  162. self.session = nil;
  163. }
  164. #pragma mark - Private
  165. - (NSDictionary *)checkinParametersWithExistingCheckin:
  166. (nullable FIRMessagingCheckinPreferences *)checkinPreferences {
  167. NSString *deviceModel = [GULAppEnvironmentUtil deviceModel];
  168. NSString *systemVersion = [GULAppEnvironmentUtil systemVersion];
  169. NSString *osVersion = [NSString stringWithFormat:@"IOS_%@", systemVersion];
  170. // Get locale from GCM if GCM exists else use system API.
  171. NSString *locale = FIRMessagingCurrentLocale();
  172. NSInteger userNumber = 0; // Multi Profile may change this.
  173. NSInteger userSerialNumber = 0; // Multi Profile may change this
  174. NSString *timeZone = [NSTimeZone localTimeZone].name;
  175. int64_t lastCheckingTimestampMillis = checkinPreferences.lastCheckinTimestampMillis;
  176. NSDictionary *checkinParameters = @{
  177. @"checkin" : @{
  178. @"iosbuild" : @{@"model" : deviceModel, @"os_version" : osVersion},
  179. @"type" : @(kCheckinType),
  180. @"user_number" : @(userNumber),
  181. @"last_checkin_msec" : @(lastCheckingTimestampMillis),
  182. },
  183. @"fragment" : @(kFragment),
  184. @"locale" : locale,
  185. @"version" : @(kCheckinVersion),
  186. @"digest" : checkinPreferences.digest ?: @"",
  187. @"time_zone" : timeZone,
  188. @"user_serial_number" : @(userSerialNumber),
  189. @"id" : @([checkinPreferences.deviceID longLongValue]),
  190. @"security_token" : @([checkinPreferences.secretToken longLongValue]),
  191. };
  192. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService006, @"Checkin parameters: %@",
  193. checkinParameters);
  194. return checkinParameters;
  195. }
  196. @end