Aucune description

FIRInstanceIDTokenFetchOperation.m 8.7KB

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