FIRMessagingCheckinService.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. NSURLSession *_session;
  38. }
  39. @end
  40. @implementation FIRMessagingCheckinService
  41. - (void)dealloc {
  42. [_session invalidateAndCancel];
  43. }
  44. - (void)checkinWithExistingCheckin:(FIRMessagingCheckinPreferences *)existingCheckin
  45. completion:(FIRMessagingDeviceCheckinCompletion)completion {
  46. NSURL *url = [NSURL URLWithString:kDeviceCheckinURL];
  47. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  48. [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  49. NSDictionary *checkinParameters = [self checkinParametersWithExistingCheckin:existingCheckin];
  50. NSData *checkinData = [NSJSONSerialization dataWithJSONObject:checkinParameters
  51. options:0
  52. error:nil];
  53. request.HTTPMethod = @"POST";
  54. request.HTTPBody = checkinData;
  55. void (^handler)(NSData *, NSURLResponse *, NSError *) =
  56. ^(NSData *data, NSURLResponse *response, NSError *error) {
  57. if (error) {
  58. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService000,
  59. @"Device checkin HTTP fetch error. Error Code: %ld",
  60. (long)error.code);
  61. if (completion) {
  62. completion(nil, error);
  63. }
  64. return;
  65. }
  66. NSError *serializationError = nil;
  67. NSDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data
  68. options:0
  69. error:&serializationError];
  70. if (serializationError) {
  71. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService001,
  72. @"Error serializing json object. Error Code: %ld",
  73. (long)serializationError.code);
  74. if (completion) {
  75. completion(nil, serializationError);
  76. }
  77. return;
  78. }
  79. NSString *deviceAuthID = [dataResponse[@"android_id"] stringValue];
  80. NSString *secretToken = [dataResponse[@"security_token"] stringValue];
  81. if ([deviceAuthID length] == 0) {
  82. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  83. failureReason:@"Invalid device auth ID."];
  84. if (completion) {
  85. completion(nil, error);
  86. }
  87. return;
  88. }
  89. int64_t lastCheckinTimestampMillis = [dataResponse[@"time_msec"] longLongValue];
  90. int64_t currentTimestampMillis = FIRMessagingCurrentTimestampInMilliseconds();
  91. // Somehow the server clock gets out of sync with the device clock.
  92. // Reset the last checkin timestamp in case this happens.
  93. if (lastCheckinTimestampMillis > currentTimestampMillis) {
  94. FIRMessagingLoggerDebug(
  95. kFIRMessagingMessageCodeService002, @"Invalid last checkin timestamp %@ in future.",
  96. [NSDate dateWithTimeIntervalSince1970:lastCheckinTimestampMillis / 1000.0]);
  97. lastCheckinTimestampMillis = currentTimestampMillis;
  98. }
  99. NSString *deviceDataVersionInfo = dataResponse[@"device_data_version_info"] ?: @"";
  100. NSString *digest = dataResponse[@"digest"] ?: @"";
  101. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService003,
  102. @"Checkin successful with authId: %@, "
  103. @"digest: %@, "
  104. @"lastCheckinTimestamp: %lld",
  105. deviceAuthID, digest, lastCheckinTimestampMillis);
  106. NSString *versionInfo = dataResponse[@"version_info"] ?: @"";
  107. NSMutableDictionary *gservicesData = [NSMutableDictionary dictionary];
  108. // Read gServices data.
  109. NSArray *flatSettings = dataResponse[@"setting"];
  110. for (NSDictionary *dict in flatSettings) {
  111. if (dict[@"name"] && dict[@"value"]) {
  112. gservicesData[dict[@"name"]] = dict[@"value"];
  113. } else {
  114. FIRMessagingLoggerDebug(kFIRMessagingInvalidSettingResponse,
  115. @"Invalid setting in checkin response: (%@: %@)", dict[@"name"],
  116. dict[@"value"]);
  117. }
  118. }
  119. FIRMessagingCheckinPreferences *checkinPreferences =
  120. [[FIRMessagingCheckinPreferences alloc] initWithDeviceID:deviceAuthID
  121. secretToken:secretToken];
  122. NSDictionary *preferences = @{
  123. kFIRMessagingDigestStringKey : digest,
  124. kFIRMessagingVersionInfoStringKey : versionInfo,
  125. kFIRMessagingLastCheckinTimeKey : @(lastCheckinTimestampMillis),
  126. kFIRMessagingGServicesDictionaryKey : gservicesData,
  127. kFIRMessagingDeviceDataVersionKey : deviceDataVersionInfo,
  128. };
  129. [checkinPreferences updateWithCheckinPlistContents:preferences];
  130. if (completion) {
  131. completion(checkinPreferences, nil);
  132. }
  133. };
  134. NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
  135. config.timeoutIntervalForResource = 60.0f; // 1 minute
  136. _session = [NSURLSession sessionWithConfiguration:config];
  137. _session.sessionDescription = @"com.google.iid-checkin";
  138. NSURLSessionDataTask *task = [_session dataTaskWithRequest:request completionHandler:handler];
  139. [task resume];
  140. }
  141. - (void)stopFetching {
  142. [_session invalidateAndCancel];
  143. // The session cannot be reused after invalidation. Dispose it to prevent accident reusing.
  144. _session = nil;
  145. }
  146. #pragma mark - Private
  147. - (NSDictionary *)checkinParametersWithExistingCheckin:
  148. (nullable FIRMessagingCheckinPreferences *)checkinPreferences {
  149. NSString *deviceModel = [GULAppEnvironmentUtil deviceModel];
  150. NSString *systemVersion = [GULAppEnvironmentUtil systemVersion];
  151. NSString *osVersion = [NSString stringWithFormat:@"IOS_%@", systemVersion];
  152. // Get locale from GCM if GCM exists else use system API.
  153. NSString *locale = FIRMessagingCurrentLocale();
  154. NSInteger userNumber = 0; // Multi Profile may change this.
  155. NSInteger userSerialNumber = 0; // Multi Profile may change this
  156. NSString *timeZone = [NSTimeZone localTimeZone].name;
  157. int64_t lastCheckingTimestampMillis = checkinPreferences.lastCheckinTimestampMillis;
  158. NSDictionary *checkinParameters = @{
  159. @"checkin" : @{
  160. @"iosbuild" : @{@"model" : deviceModel, @"os_version" : osVersion},
  161. @"type" : @(kCheckinType),
  162. @"user_number" : @(userNumber),
  163. @"last_checkin_msec" : @(lastCheckingTimestampMillis),
  164. },
  165. @"fragment" : @(kFragment),
  166. @"locale" : locale,
  167. @"version" : @(kCheckinVersion),
  168. @"digest" : checkinPreferences.digest ?: @"",
  169. @"time_zone" : timeZone,
  170. @"user_serial_number" : @(userSerialNumber),
  171. @"id" : @([checkinPreferences.deviceID longLongValue]),
  172. @"security_token" : @([checkinPreferences.secretToken longLongValue]),
  173. };
  174. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeService006, @"Checkin parameters: %@",
  175. checkinParameters);
  176. return checkinParameters;
  177. }
  178. @end