FIRInstanceIDCheckinService.m 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 "FIRInstanceIDCheckinService.h"
  17. #import "FIRInstanceIDCheckinPreferences+Internal.h"
  18. #import "FIRInstanceIDCheckinPreferences_Private.h"
  19. #import "FIRInstanceIDDefines.h"
  20. #import "FIRInstanceIDLogger.h"
  21. #import "FIRInstanceIDStore.h"
  22. #import "FIRInstanceIDUtilities.h"
  23. #import "NSError+FIRInstanceID.h"
  24. static NSString *const kDeviceCheckinURL = @"https://device-provisioning.googleapis.com/checkin";
  25. // keys in Checkin preferences
  26. NSString *const kFIRInstanceIDDeviceAuthIdKey = @"GMSInstanceIDDeviceAuthIdKey";
  27. NSString *const kFIRInstanceIDSecretTokenKey = @"GMSInstanceIDSecretTokenKey";
  28. NSString *const kFIRInstanceIDDigestStringKey = @"GMSInstanceIDDigestKey";
  29. NSString *const kFIRInstanceIDLastCheckinTimeKey = @"GMSInstanceIDLastCheckinTimestampKey";
  30. NSString *const kFIRInstanceIDVersionInfoStringKey = @"GMSInstanceIDVersionInfo";
  31. NSString *const kFIRInstanceIDGServicesDictionaryKey = @"GMSInstanceIDGServicesData";
  32. NSString *const kFIRInstanceIDDeviceDataVersionKey = @"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. static FIRInstanceIDURLRequestTestBlock testBlock;
  37. @interface FIRInstanceIDCheckinService ()
  38. @property(nonatomic, readwrite, strong) NSURLSession *session;
  39. @end
  40. @implementation FIRInstanceIDCheckinService
  41. ;
  42. - (instancetype)init {
  43. self = [super init];
  44. if (self) {
  45. // Create an URLSession once, even though checkin should happen about once a day
  46. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  47. config.timeoutIntervalForResource = 60.0f; // 1 minute
  48. config.allowsCellularAccess = YES;
  49. _session = [NSURLSession sessionWithConfiguration:config];
  50. _session.sessionDescription = @"com.google.iid-checkin";
  51. }
  52. return self;
  53. }
  54. - (void)dealloc {
  55. testBlock = nil;
  56. [self.session invalidateAndCancel];
  57. }
  58. - (void)checkinWithExistingCheckin:(FIRInstanceIDCheckinPreferences *)existingCheckin
  59. completion:(FIRInstanceIDDeviceCheckinCompletion)completion {
  60. _FIRInstanceIDDevAssert(completion != nil, @"completion required");
  61. NSURL *url = [NSURL URLWithString:kDeviceCheckinURL];
  62. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  63. [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  64. NSDictionary *checkinParameters = [self checkinParametersWithExistingCheckin:existingCheckin];
  65. NSData *checkinData = [NSJSONSerialization dataWithJSONObject:checkinParameters
  66. options:0
  67. error:nil];
  68. request.HTTPMethod = @"POST";
  69. request.HTTPBody = checkinData;
  70. void (^handler)(NSData *, NSURLResponse *, NSError *) =
  71. ^(NSData *data, NSURLResponse *response, NSError *error) {
  72. if (error) {
  73. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService000,
  74. @"Device checkin HTTP fetch error. Error Code: %ld",
  75. (long)error.code);
  76. completion(nil, error);
  77. return;
  78. }
  79. NSError *serializationError;
  80. NSDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data
  81. options:0
  82. error:&serializationError];
  83. if (serializationError) {
  84. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService001,
  85. @"Error serializing json object. Error Code: %ld",
  86. _FIRInstanceID_L(serializationError.code));
  87. completion(nil, serializationError);
  88. return;
  89. }
  90. NSString *deviceAuthID = [dataResponse[@"android_id"] stringValue];
  91. NSString *secretToken = [dataResponse[@"security_token"] stringValue];
  92. if ([deviceAuthID length] == 0) {
  93. NSError *error =
  94. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidRequest];
  95. completion(nil, error);
  96. return;
  97. }
  98. int64_t lastCheckinTimestampMillis = [dataResponse[@"time_msec"] longLongValue];
  99. int64_t currentTimestampMillis = FIRInstanceIDCurrentTimestampInMilliseconds();
  100. // Somehow the server clock gets out of sync with the device clock.
  101. // Reset the last checkin timestamp in case this happens.
  102. if (lastCheckinTimestampMillis > currentTimestampMillis) {
  103. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService002,
  104. @"Invalid last checkin timestamp in future.");
  105. lastCheckinTimestampMillis = currentTimestampMillis;
  106. }
  107. NSString *deviceDataVersionInfo = dataResponse[@"device_data_version_info"] ?: @"";
  108. NSString *digest = dataResponse[@"digest"] ?: @"";
  109. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService003,
  110. @"Checkin successful with authId: %@, "
  111. @"digest: %@, "
  112. @"lastCheckinTimestamp: %lld",
  113. deviceAuthID, digest, lastCheckinTimestampMillis);
  114. NSString *versionInfo = dataResponse[@"version_info"] ?: @"";
  115. NSMutableDictionary *gservicesData = [NSMutableDictionary dictionary];
  116. // Read gServices data.
  117. NSArray *flatSettings = dataResponse[@"setting"];
  118. for (NSDictionary *dict in flatSettings) {
  119. if (dict[@"name"] && dict[@"value"]) {
  120. gservicesData[dict[@"name"]] = dict[@"value"];
  121. } else {
  122. _FIRInstanceIDDevAssert(NO, @"Invalid setting in checkin response: (%@: %@)",
  123. dict[@"name"], dict[@"value"]);
  124. }
  125. }
  126. FIRInstanceIDCheckinPreferences *checkinPreferences =
  127. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:deviceAuthID
  128. secretToken:secretToken];
  129. NSDictionary *preferences = @{
  130. kFIRInstanceIDDigestStringKey : digest,
  131. kFIRInstanceIDVersionInfoStringKey : versionInfo,
  132. kFIRInstanceIDLastCheckinTimeKey : @(lastCheckinTimestampMillis),
  133. kFIRInstanceIDGServicesDictionaryKey : gservicesData,
  134. kFIRInstanceIDDeviceDataVersionKey : deviceDataVersionInfo,
  135. };
  136. [checkinPreferences updateWithCheckinPlistContents:preferences];
  137. completion(checkinPreferences, nil);
  138. };
  139. // Test block
  140. if (testBlock) {
  141. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService005,
  142. @"Test block set, will not hit the server");
  143. testBlock(request, handler);
  144. return;
  145. }
  146. NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:handler];
  147. [task resume];
  148. }
  149. - (void)stopFetching {
  150. [self.session invalidateAndCancel];
  151. }
  152. #pragma mark - Private
  153. - (NSDictionary *)checkinParametersWithExistingCheckin:
  154. (nullable FIRInstanceIDCheckinPreferences *)checkinPreferences {
  155. NSString *deviceModel = FIRInstanceIDDeviceModel();
  156. NSString *systemVersion = FIRInstanceIDOperatingSystemVersion();
  157. NSString *osVersion = [NSString stringWithFormat:@"IOS_%@", systemVersion];
  158. // Get locale from GCM if GCM exists else use system API.
  159. NSString *locale = FIRInstanceIDCurrentLocale();
  160. NSInteger userNumber = 0; // Multi Profile may change this.
  161. NSInteger userSerialNumber = 0; // Multi Profile may change this
  162. uint32_t loggingID = arc4random();
  163. NSString *timeZone = [NSTimeZone localTimeZone].name;
  164. int64_t lastCheckingTimestampMillis = checkinPreferences.lastCheckinTimestampMillis;
  165. NSDictionary *checkinParameters = @{
  166. @"checkin" : @{
  167. @"iosbuild" : @{@"model" : deviceModel, @"os_version" : osVersion},
  168. @"type" : @(kCheckinType),
  169. @"user_number" : @(userNumber),
  170. @"last_checkin_msec" : @(lastCheckingTimestampMillis),
  171. },
  172. @"fragment" : @(kFragment),
  173. @"logging_id" : @(loggingID),
  174. @"locale" : locale,
  175. @"version" : @(kCheckinVersion),
  176. @"digest" : checkinPreferences.digest ?: @"",
  177. @"timezone" : timeZone,
  178. @"user_serial_number" : @(userSerialNumber),
  179. @"id" : @([checkinPreferences.deviceID longLongValue]),
  180. @"security_token" : @([checkinPreferences.secretToken longLongValue]),
  181. };
  182. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService006, @"Checkin parameters: %@",
  183. checkinParameters);
  184. return checkinParameters;
  185. }
  186. + (void)setCheckinTestBlock:(FIRInstanceIDURLRequestTestBlock)block {
  187. testBlock = [block copy];
  188. }
  189. @end