FIRInstanceIDTokenFetchOperation.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 "FIRInstanceIDTokenFetchOperation.h"
  17. #import "FIRInstanceIDCheckinPreferences.h"
  18. #import "FIRInstanceIDConstants.h"
  19. #import "FIRInstanceIDDefines.h"
  20. #import "FIRInstanceIDLogger.h"
  21. #import "FIRInstanceIDTokenOperation+Private.h"
  22. #import "FIRInstanceIDURLQueryItem.h"
  23. #import "FIRInstanceIDUtilities.h"
  24. #import "NSError+FIRInstanceID.h"
  25. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  26. // We can have a static int since this error should theoretically only
  27. // happen once (for the first time). If it repeats there is something
  28. // else that is wrong.
  29. static int phoneRegistrationErrorRetryCount = 0;
  30. static const int kMaxPhoneRegistrationErrorRetryCount = 10;
  31. NSString *const kFIRInstanceIDFirebaseUserAgentKey = @"X-firebase-client";
  32. NSString *const kFIRInstanceIDFirebaseHeartbeatKey = @"X-firebase-client-log-type";
  33. NSString *const kFIRInstanceIDHeartbeatTag = @"fire-iid";
  34. @implementation FIRInstanceIDTokenFetchOperation
  35. - (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
  36. scope:(NSString *)scope
  37. options:(nullable NSDictionary<NSString *, NSString *> *)options
  38. checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
  39. instanceID:(NSString *)instanceID {
  40. self = [super initWithAction:FIRInstanceIDTokenActionFetch
  41. forAuthorizedEntity:authorizedEntity
  42. scope:scope
  43. options:options
  44. checkinPreferences:checkinPreferences
  45. instanceID:instanceID];
  46. if (self) {
  47. }
  48. return self;
  49. }
  50. - (void)performTokenOperation {
  51. NSMutableURLRequest *request = [self tokenRequest];
  52. NSString *checkinVersionInfo = self.checkinPreferences.versionInfo;
  53. [request setValue:checkinVersionInfo forHTTPHeaderField:@"info"];
  54. [request setValue:[FIRApp firebaseUserAgent]
  55. forHTTPHeaderField:kFIRInstanceIDFirebaseUserAgentKey];
  56. [request setValue:@([FIRHeartbeatInfo heartbeatCodeForTag:kFIRInstanceIDHeartbeatTag]).stringValue
  57. forHTTPHeaderField:kFIRInstanceIDFirebaseHeartbeatKey];
  58. // Build form-encoded body
  59. NSString *deviceAuthID = self.checkinPreferences.deviceID;
  60. NSMutableArray<FIRInstanceIDURLQueryItem *> *queryItems =
  61. [[self class] standardQueryItemsWithDeviceID:deviceAuthID scope:self.scope];
  62. [queryItems addObject:[FIRInstanceIDURLQueryItem queryItemWithName:@"sender"
  63. value:self.authorizedEntity]];
  64. [queryItems addObject:[FIRInstanceIDURLQueryItem queryItemWithName:@"X-subtype"
  65. value:self.authorizedEntity]];
  66. [queryItems addObjectsFromArray:[self queryItemsWithInstanceID:self.instanceID]];
  67. // Create query items from passed-in options
  68. id apnsTokenData = self.options[kFIRInstanceIDTokenOptionsAPNSKey];
  69. id apnsSandboxValue = self.options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey];
  70. if ([apnsTokenData isKindOfClass:[NSData class]] &&
  71. [apnsSandboxValue isKindOfClass:[NSNumber class]]) {
  72. NSString *APNSString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  73. apnsTokenData, ((NSNumber *)apnsSandboxValue).boolValue);
  74. // The name of the query item happens to be the same as the dictionary key
  75. FIRInstanceIDURLQueryItem *item =
  76. [FIRInstanceIDURLQueryItem queryItemWithName:kFIRInstanceIDTokenOptionsAPNSKey
  77. value:APNSString];
  78. [queryItems addObject:item];
  79. }
  80. id firebaseAppID = self.options[kFIRInstanceIDTokenOptionsFirebaseAppIDKey];
  81. if ([firebaseAppID isKindOfClass:[NSString class]]) {
  82. // The name of the query item happens to be the same as the dictionary key
  83. FIRInstanceIDURLQueryItem *item =
  84. [FIRInstanceIDURLQueryItem queryItemWithName:kFIRInstanceIDTokenOptionsFirebaseAppIDKey
  85. value:(NSString *)firebaseAppID];
  86. [queryItems addObject:item];
  87. }
  88. NSString *content = FIRInstanceIDQueryFromQueryItems(queryItems);
  89. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  90. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationFetchRequest,
  91. @"Register request to %@ content: %@", FIRInstanceIDRegisterServer(),
  92. content);
  93. FIRInstanceID_WEAKIFY(self);
  94. void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  95. ^(NSData *data, NSURLResponse *response, NSError *error) {
  96. FIRInstanceID_STRONGIFY(self);
  97. [self handleResponseWithData:data response:response error:error];
  98. };
  99. // Test block
  100. if (self.testBlock) {
  101. self.testBlock(request, requestHandler);
  102. return;
  103. }
  104. NSURLSession *session = [FIRInstanceIDTokenOperation sharedURLSession];
  105. self.dataTask = [session dataTaskWithRequest:request completionHandler:requestHandler];
  106. [self.dataTask resume];
  107. }
  108. #pragma mark - Request Handling
  109. - (void)handleResponseWithData:(NSData *)data
  110. response:(NSURLResponse *)response
  111. error:(NSError *)error {
  112. if (error) {
  113. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationRequestError,
  114. @"Token fetch HTTP error. Error Code: %ld", (long)error.code);
  115. [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
  116. return;
  117. }
  118. NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  119. if (dataResponse.length == 0) {
  120. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
  121. [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:error];
  122. return;
  123. }
  124. NSDictionary *parsedResponse = [self parseFetchTokenResponse:dataResponse];
  125. if ([parsedResponse[@"token"] length]) {
  126. [self finishWithResult:FIRInstanceIDTokenOperationSucceeded
  127. token:parsedResponse[@"token"]
  128. error:nil];
  129. return;
  130. }
  131. NSString *errorValue = parsedResponse[@"Error"];
  132. NSError *responseError;
  133. if (errorValue.length) {
  134. NSArray *errorComponents = [errorValue componentsSeparatedByString:@":"];
  135. // HACK (Kansas replication delay), PHONE_REGISTRATION_ERROR on App
  136. // uninstall and reinstall.
  137. if ([errorComponents containsObject:@"PHONE_REGISTRATION_ERROR"]) {
  138. // Encountered issue http://b/27043795
  139. // Retry register until successful or another error encountered or a
  140. // certain number of tries are over.
  141. if (phoneRegistrationErrorRetryCount < kMaxPhoneRegistrationErrorRetryCount) {
  142. const int nextRetryInterval = 1 << phoneRegistrationErrorRetryCount;
  143. FIRInstanceID_WEAKIFY(self);
  144. dispatch_after(
  145. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(nextRetryInterval * NSEC_PER_SEC)),
  146. dispatch_get_main_queue(), ^{
  147. FIRInstanceID_STRONGIFY(self);
  148. phoneRegistrationErrorRetryCount++;
  149. [self performTokenOperation];
  150. });
  151. return;
  152. }
  153. } else if ([errorComponents containsObject:kFIRInstanceID_CMD_RST]) {
  154. // Server detected the identity we use is no longer valid.
  155. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  156. [center postNotificationName:kFIRInstanceIDIdentityInvalidatedNotification object:nil];
  157. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal001,
  158. @"Identity is invalid. Server request identity reset.");
  159. responseError =
  160. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidIdentity];
  161. }
  162. }
  163. if (!responseError) {
  164. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenFetchOperationBadResponse,
  165. @"Invalid fetch response, expected 'token' or 'Error' key");
  166. responseError = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown];
  167. }
  168. [self finishWithResult:FIRInstanceIDTokenOperationError token:nil error:responseError];
  169. }
  170. // expect a response e.g. "token=<reg id>\nGOOG.ttl=123"
  171. - (NSDictionary *)parseFetchTokenResponse:(NSString *)response {
  172. NSArray *lines = [response componentsSeparatedByString:@"\n"];
  173. NSMutableDictionary *parsedResponse = [NSMutableDictionary dictionary];
  174. for (NSString *line in lines) {
  175. NSArray *keyAndValue = [line componentsSeparatedByString:@"="];
  176. if ([keyAndValue count] > 1) {
  177. parsedResponse[keyAndValue[0]] = keyAndValue[1];
  178. }
  179. }
  180. return parsedResponse;
  181. }
  182. @end