FIRMessagingTokenFetchOperation.m 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 "FirebaseMessaging/Sources/Token/FIRMessagingTokenFetchOperation.h"
  17. #import "FirebaseMessaging/Sources/FIRMessagingCode.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  21. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  22. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  23. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinPreferences.h"
  24. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenOperation.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 kFIRMessagingFirebaseUserAgentKey = @"X-firebase-client";
  32. NSString *const kFIRMessagingFirebaseHeartbeatKey = @"X-firebase-client-log-type";
  33. NSString *const kFIRMessagingHeartbeatTag = @"fire-iid";
  34. @implementation FIRMessagingTokenFetchOperation
  35. - (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
  36. scope:(NSString *)scope
  37. options:(nullable NSDictionary<NSString *, NSString *> *)options
  38. checkinPreferences:(FIRMessagingCheckinPreferences *)checkinPreferences
  39. instanceID:(NSString *)instanceID {
  40. return [super initWithAction:FIRMessagingTokenActionFetch
  41. forAuthorizedEntity:authorizedEntity
  42. scope:scope
  43. options:options
  44. checkinPreferences:checkinPreferences
  45. instanceID:instanceID];
  46. }
  47. - (void)performTokenOperation {
  48. NSMutableURLRequest *request = [self tokenRequest];
  49. NSString *checkinVersionInfo = self.checkinPreferences.versionInfo;
  50. [request setValue:checkinVersionInfo forHTTPHeaderField:@"info"];
  51. [request setValue:[FIRApp firebaseUserAgent]
  52. forHTTPHeaderField:kFIRMessagingFirebaseUserAgentKey];
  53. [request setValue:@([FIRHeartbeatInfo heartbeatCodeForTag:kFIRMessagingHeartbeatTag]).stringValue
  54. forHTTPHeaderField:kFIRMessagingFirebaseHeartbeatKey];
  55. // Build form-encoded body
  56. NSString *deviceAuthID = self.checkinPreferences.deviceID;
  57. NSMutableArray<NSURLQueryItem *> *queryItems =
  58. [[self class] standardQueryItemsWithDeviceID:deviceAuthID scope:self.scope];
  59. [queryItems addObject:[NSURLQueryItem queryItemWithName:@"sender" value:self.authorizedEntity]];
  60. [queryItems addObject:[NSURLQueryItem queryItemWithName:@"X-subtype"
  61. value:self.authorizedEntity]];
  62. if (self.instanceID.length > 0) {
  63. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFIRMessagingParamInstanceID
  64. value:self.instanceID]];
  65. }
  66. // Create query items from passed-in options
  67. id apnsTokenData = self.options[kFIRMessagingTokenOptionsAPNSKey];
  68. id apnsSandboxValue = self.options[kFIRMessagingTokenOptionsAPNSIsSandboxKey];
  69. if ([apnsTokenData isKindOfClass:[NSData class]] &&
  70. [apnsSandboxValue isKindOfClass:[NSNumber class]]) {
  71. NSString *APNSString = FIRMessagingAPNSTupleStringForTokenAndServerType(
  72. apnsTokenData, ((NSNumber *)apnsSandboxValue).boolValue);
  73. // The name of the query item happens to be the same as the dictionary key
  74. NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:kFIRMessagingTokenOptionsAPNSKey
  75. value:APNSString];
  76. [queryItems addObject:item];
  77. }
  78. id firebaseAppID = self.options[kFIRMessagingTokenOptionsFirebaseAppIDKey];
  79. if ([firebaseAppID isKindOfClass:[NSString class]]) {
  80. // The name of the query item happens to be the same as the dictionary key
  81. NSURLQueryItem *item =
  82. [NSURLQueryItem queryItemWithName:kFIRMessagingTokenOptionsFirebaseAppIDKey
  83. value:(NSString *)firebaseAppID];
  84. [queryItems addObject:item];
  85. }
  86. NSURLComponents *components = [[NSURLComponents alloc] init];
  87. components.queryItems = queryItems;
  88. NSString *content = components.query;
  89. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  90. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationFetchRequest,
  91. @"Register request to %@ content: %@", FIRMessagingTokenRegisterServer(),
  92. content);
  93. FIRMessaging_WEAKIFY(self);
  94. void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  95. ^(NSData *data, NSURLResponse *response, NSError *error) {
  96. FIRMessaging_STRONGIFY(self);
  97. [self handleResponseWithData:data response:response error:error];
  98. };
  99. NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
  100. config.timeoutIntervalForResource = 60.0f; // 1 minute
  101. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  102. self.dataTask = [session dataTaskWithRequest:request completionHandler:requestHandler];
  103. [self.dataTask resume];
  104. }
  105. #pragma mark - Request Handling
  106. - (void)handleResponseWithData:(NSData *)data
  107. response:(NSURLResponse *)response
  108. error:(NSError *)error {
  109. if (error) {
  110. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationRequestError,
  111. @"Token fetch HTTP error. Error Code: %ld", (long)error.code);
  112. [self finishWithResult:FIRMessagingTokenOperationError token:nil error:error];
  113. return;
  114. }
  115. NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  116. if (dataResponse.length == 0) {
  117. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  118. failureReason:@"Empty response."];
  119. [self finishWithResult:FIRMessagingTokenOperationError token:nil error:error];
  120. return;
  121. }
  122. NSDictionary *parsedResponse = [self parseFetchTokenResponse:dataResponse];
  123. if ([parsedResponse[@"token"] length]) {
  124. [self finishWithResult:FIRMessagingTokenOperationSucceeded
  125. token:parsedResponse[@"token"]
  126. error:nil];
  127. return;
  128. }
  129. NSString *errorValue = parsedResponse[@"Error"];
  130. NSError *responseError = nil;
  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. FIRMessaging_WEAKIFY(self);
  142. dispatch_after(
  143. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(nextRetryInterval * NSEC_PER_SEC)),
  144. dispatch_get_main_queue(), ^{
  145. FIRMessaging_STRONGIFY(self);
  146. phoneRegistrationErrorRetryCount++;
  147. [self performTokenOperation];
  148. });
  149. return;
  150. }
  151. } else if ([errorComponents containsObject:kFIRMessaging_CMD_RST]) {
  152. NSString *failureReason = @"Identity is invalid. Server request identity reset.";
  153. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInternal001, @"%@", failureReason);
  154. responseError = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidIdentity
  155. failureReason:failureReason];
  156. }
  157. }
  158. if (!responseError) {
  159. NSString *failureReason = @"Invalid fetch response, expected 'token' or 'Error' key";
  160. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationBadResponse, @"%@",
  161. failureReason);
  162. responseError = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  163. failureReason:failureReason];
  164. }
  165. [self finishWithResult:FIRMessagingTokenOperationError token:nil error:responseError];
  166. }
  167. // expect a response e.g. "token=<reg id>\nGOOG.ttl=123"
  168. - (NSDictionary *)parseFetchTokenResponse:(NSString *)response {
  169. NSArray *lines = [response componentsSeparatedByString:@"\n"];
  170. NSMutableDictionary *parsedResponse = [NSMutableDictionary dictionary];
  171. for (NSString *line in lines) {
  172. NSArray *keyAndValue = [line componentsSeparatedByString:@"="];
  173. if ([keyAndValue count] > 1) {
  174. parsedResponse[keyAndValue[0]] = keyAndValue[1];
  175. }
  176. }
  177. return parsedResponse;
  178. }
  179. @end