Nav apraksta

FIRInstanceIDCheckinService.m 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. if (self.session == nil) {
  61. FIRInstanceIDLoggerError(kFIRInstanceIDInvalidNetworkSession,
  62. @"Inconsistent state: NSURLSession has been invalidated");
  63. NSError *error =
  64. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeRegistrarFailedToCheckIn];
  65. if (completion) {
  66. completion(nil, error);
  67. }
  68. return;
  69. }
  70. NSURL *url = [NSURL URLWithString:kDeviceCheckinURL];
  71. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  72. [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
  73. NSDictionary *checkinParameters = [self checkinParametersWithExistingCheckin:existingCheckin];
  74. NSData *checkinData = [NSJSONSerialization dataWithJSONObject:checkinParameters
  75. options:0
  76. error:nil];
  77. request.HTTPMethod = @"POST";
  78. request.HTTPBody = checkinData;
  79. void (^handler)(NSData *, NSURLResponse *, NSError *) =
  80. ^(NSData *data, NSURLResponse *response, NSError *error) {
  81. if (error) {
  82. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService000,
  83. @"Device checkin HTTP fetch error. Error Code: %ld",
  84. (long)error.code);
  85. if (completion) {
  86. completion(nil, error);
  87. }
  88. return;
  89. }
  90. NSError *serializationError;
  91. NSDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data
  92. options:0
  93. error:&serializationError];
  94. if (serializationError) {
  95. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService001,
  96. @"Error serializing json object. Error Code: %ld",
  97. _FIRInstanceID_L(serializationError.code));
  98. if (completion) {
  99. completion(nil, serializationError);
  100. }
  101. return;
  102. }
  103. NSString *deviceAuthID = [dataResponse[@"android_id"] stringValue];
  104. NSString *secretToken = [dataResponse[@"security_token"] stringValue];
  105. if ([deviceAuthID length] == 0) {
  106. NSError *error =
  107. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidRequest];
  108. if (completion) {
  109. completion(nil, error);
  110. }
  111. return;
  112. }
  113. int64_t lastCheckinTimestampMillis = [dataResponse[@"time_msec"] longLongValue];
  114. int64_t currentTimestampMillis = FIRInstanceIDCurrentTimestampInMilliseconds();
  115. // Somehow the server clock gets out of sync with the device clock.
  116. // Reset the last checkin timestamp in case this happens.
  117. if (lastCheckinTimestampMillis > currentTimestampMillis) {
  118. FIRInstanceIDLoggerDebug(
  119. kFIRInstanceIDMessageCodeService002, @"Invalid last checkin timestamp %@ in future.",
  120. [NSDate dateWithTimeIntervalSince1970:lastCheckinTimestampMillis / 1000.0]);
  121. lastCheckinTimestampMillis = currentTimestampMillis;
  122. }
  123. NSString *deviceDataVersionInfo = dataResponse[@"device_data_version_info"] ?: @"";
  124. NSString *digest = dataResponse[@"digest"] ?: @"";
  125. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService003,
  126. @"Checkin successful with authId: %@, "
  127. @"digest: %@, "
  128. @"lastCheckinTimestamp: %lld",
  129. deviceAuthID, digest, lastCheckinTimestampMillis);
  130. NSString *versionInfo = dataResponse[@"version_info"] ?: @"";
  131. NSMutableDictionary *gservicesData = [NSMutableDictionary dictionary];
  132. // Read gServices data.
  133. NSArray *flatSettings = dataResponse[@"setting"];
  134. for (NSDictionary *dict in flatSettings) {
  135. if (dict[@"name"] && dict[@"value"]) {
  136. gservicesData[dict[@"name"]] = dict[@"value"];
  137. } else {
  138. FIRInstanceIDLoggerDebug(kFIRInstanceIDInvalidSettingResponse,
  139. @"Invalid setting in checkin response: (%@: %@)",
  140. dict[@"name"], dict[@"value"]);
  141. }
  142. }
  143. FIRInstanceIDCheckinPreferences *checkinPreferences =
  144. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:deviceAuthID
  145. secretToken:secretToken];
  146. NSDictionary *preferences = @{
  147. kFIRInstanceIDDigestStringKey : digest,
  148. kFIRInstanceIDVersionInfoStringKey : versionInfo,
  149. kFIRInstanceIDLastCheckinTimeKey : @(lastCheckinTimestampMillis),
  150. kFIRInstanceIDGServicesDictionaryKey : gservicesData,
  151. kFIRInstanceIDDeviceDataVersionKey : deviceDataVersionInfo,
  152. };
  153. [checkinPreferences updateWithCheckinPlistContents:preferences];
  154. if (completion) {
  155. completion(checkinPreferences, nil);
  156. }
  157. };
  158. // Test block
  159. if (testBlock) {
  160. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService005,
  161. @"Test block set, will not hit the server");
  162. testBlock(request, handler);
  163. return;
  164. }
  165. NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:handler];
  166. [task resume];
  167. }
  168. - (void)stopFetching {
  169. [self.session invalidateAndCancel];
  170. // The session cannot be reused after invalidation. Dispose it to prevent accident reusing.
  171. self.session = nil;
  172. }
  173. #pragma mark - Private
  174. - (NSDictionary *)checkinParametersWithExistingCheckin:
  175. (nullable FIRInstanceIDCheckinPreferences *)checkinPreferences {
  176. NSString *deviceModel = FIRInstanceIDDeviceModel();
  177. NSString *systemVersion = FIRInstanceIDOperatingSystemVersion();
  178. NSString *osVersion = [NSString stringWithFormat:@"IOS_%@", systemVersion];
  179. // Get locale from GCM if GCM exists else use system API.
  180. NSString *locale = FIRInstanceIDCurrentLocale();
  181. NSInteger userNumber = 0; // Multi Profile may change this.
  182. NSInteger userSerialNumber = 0; // Multi Profile may change this
  183. uint32_t loggingID = arc4random();
  184. NSString *timeZone = [NSTimeZone localTimeZone].name;
  185. int64_t lastCheckingTimestampMillis = checkinPreferences.lastCheckinTimestampMillis;
  186. NSDictionary *checkinParameters = @{
  187. @"checkin" : @{
  188. @"iosbuild" : @{@"model" : deviceModel, @"os_version" : osVersion},
  189. @"type" : @(kCheckinType),
  190. @"user_number" : @(userNumber),
  191. @"last_checkin_msec" : @(lastCheckingTimestampMillis),
  192. },
  193. @"fragment" : @(kFragment),
  194. @"logging_id" : @(loggingID),
  195. @"locale" : locale,
  196. @"version" : @(kCheckinVersion),
  197. @"digest" : checkinPreferences.digest ?: @"",
  198. @"time_zone" : timeZone,
  199. @"user_serial_number" : @(userSerialNumber),
  200. @"id" : @([checkinPreferences.deviceID longLongValue]),
  201. @"security_token" : @([checkinPreferences.secretToken longLongValue]),
  202. };
  203. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeService006, @"Checkin parameters: %@",
  204. checkinParameters);
  205. return checkinParameters;
  206. }
  207. + (void)setCheckinTestBlock:(FIRInstanceIDURLRequestTestBlock)block {
  208. testBlock = [block copy];
  209. }
  210. @end