Aucune description

FIRInstanceIDTokenFetchOperation.m 8.8KB

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