暂无描述

FIRInstanceIDTokenFetchOperation.m 9.1KB

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