FIRMessagingTokenFetchOperation.m 9.3 KB

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 "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/Extension/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. @implementation FIRMessagingTokenFetchOperation
  34. - (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
  35. scope:(NSString *)scope
  36. options:(nullable NSDictionary<NSString *, NSString *> *)options
  37. checkinPreferences:(FIRMessagingCheckinPreferences *)checkinPreferences
  38. instanceID:(NSString *)instanceID
  39. heartbeatLogger:(id<FIRHeartbeatLoggerProtocol>)heartbeatLogger {
  40. return [super initWithAction:FIRMessagingTokenActionFetch
  41. forAuthorizedEntity:authorizedEntity
  42. scope:scope
  43. options:options
  44. checkinPreferences:checkinPreferences
  45. instanceID:instanceID
  46. heartbeatLogger:heartbeatLogger];
  47. }
  48. - (void)performTokenOperation {
  49. NSMutableURLRequest *request = [self tokenRequest];
  50. NSString *checkinVersionInfo = self.checkinPreferences.versionInfo;
  51. [request setValue:checkinVersionInfo forHTTPHeaderField:@"info"];
  52. [request setValue:[FIRApp firebaseUserAgent]
  53. forHTTPHeaderField:kFIRMessagingFirebaseUserAgentKey];
  54. [request setValue:@([self.heartbeatLogger heartbeatCodeForToday]).stringValue
  55. forHTTPHeaderField:kFIRMessagingFirebaseHeartbeatKey];
  56. // Build form-encoded body
  57. NSString *deviceAuthID = self.checkinPreferences.deviceID;
  58. NSMutableArray<NSURLQueryItem *> *queryItems =
  59. [[self class] standardQueryItemsWithDeviceID:deviceAuthID scope:self.scope];
  60. [queryItems addObject:[NSURLQueryItem queryItemWithName:@"sender" value:self.authorizedEntity]];
  61. [queryItems addObject:[NSURLQueryItem queryItemWithName:@"X-subtype"
  62. value:self.authorizedEntity]];
  63. if (self.instanceID.length > 0) {
  64. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFIRMessagingParamInstanceID
  65. value:self.instanceID]];
  66. }
  67. // Create query items from passed-in options
  68. id apnsTokenData = self.options[kFIRMessagingTokenOptionsAPNSKey];
  69. id apnsSandboxValue = self.options[kFIRMessagingTokenOptionsAPNSIsSandboxKey];
  70. if ([apnsTokenData isKindOfClass:[NSData class]] &&
  71. [apnsSandboxValue isKindOfClass:[NSNumber class]]) {
  72. NSString *APNSString = FIRMessagingAPNSTupleStringForTokenAndServerType(
  73. apnsTokenData, ((NSNumber *)apnsSandboxValue).boolValue);
  74. // The name of the query item happens to be the same as the dictionary key
  75. NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:kFIRMessagingTokenOptionsAPNSKey
  76. value:APNSString];
  77. [queryItems addObject:item];
  78. }
  79. id firebaseAppID = self.options[kFIRMessagingTokenOptionsFirebaseAppIDKey];
  80. if ([firebaseAppID isKindOfClass:[NSString class]]) {
  81. // The name of the query item happens to be the same as the dictionary key
  82. NSURLQueryItem *item =
  83. [NSURLQueryItem queryItemWithName:kFIRMessagingTokenOptionsFirebaseAppIDKey
  84. value:(NSString *)firebaseAppID];
  85. [queryItems addObject:item];
  86. }
  87. NSURLComponents *components = [[NSURLComponents alloc] init];
  88. components.queryItems = queryItems;
  89. NSString *content = components.query;
  90. request.HTTPBody = [content dataUsingEncoding:NSUTF8StringEncoding];
  91. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationFetchRequest,
  92. @"Register request to %@ content: %@", FIRMessagingTokenRegisterServer(),
  93. content);
  94. FIRMessaging_WEAKIFY(self);
  95. void (^requestHandler)(NSData *, NSURLResponse *, NSError *) =
  96. ^(NSData *data, NSURLResponse *response, NSError *error) {
  97. FIRMessaging_STRONGIFY(self);
  98. [self handleResponseWithData:data response:response error:error];
  99. };
  100. NSURLSessionConfiguration *config = NSURLSessionConfiguration.defaultSessionConfiguration;
  101. config.timeoutIntervalForResource = 60.0f; // 1 minute
  102. NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
  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. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationRequestError,
  112. @"Token fetch HTTP error. Error Code: %ld", (long)error.code);
  113. [self finishWithResult:FIRMessagingTokenOperationError 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 messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  119. failureReason:@"Empty response."];
  120. [self finishWithResult:FIRMessagingTokenOperationError token:nil error:error];
  121. return;
  122. }
  123. NSDictionary *parsedResponse = [self parseFetchTokenResponse:dataResponse];
  124. if ([parsedResponse[@"token"] length]) {
  125. [self finishWithResult:FIRMessagingTokenOperationSucceeded
  126. token:parsedResponse[@"token"]
  127. error:nil];
  128. return;
  129. }
  130. NSString *errorValue = parsedResponse[@"Error"];
  131. NSError *responseError = nil;
  132. if (errorValue.length) {
  133. NSArray *errorComponents = [errorValue componentsSeparatedByString:@":"];
  134. // HACK (Kansas replication delay), PHONE_REGISTRATION_ERROR on App
  135. // uninstall and reinstall.
  136. if ([errorComponents containsObject:@"PHONE_REGISTRATION_ERROR"]) {
  137. // Encountered issue http://b/27043795
  138. // Retry register until successful or another error encountered or a
  139. // certain number of tries are over.
  140. if (phoneRegistrationErrorRetryCount < kMaxPhoneRegistrationErrorRetryCount) {
  141. const int nextRetryInterval = 1 << phoneRegistrationErrorRetryCount;
  142. FIRMessaging_WEAKIFY(self);
  143. dispatch_after(
  144. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(nextRetryInterval * NSEC_PER_SEC)),
  145. dispatch_get_main_queue(), ^{
  146. FIRMessaging_STRONGIFY(self);
  147. phoneRegistrationErrorRetryCount++;
  148. [self performTokenOperation];
  149. });
  150. return;
  151. }
  152. } else if ([errorComponents containsObject:kFIRMessaging_CMD_RST]) {
  153. NSString *failureReason = @"Identity is invalid. Server request identity reset.";
  154. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInternal001, @"%@", failureReason);
  155. responseError = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidIdentity
  156. failureReason:failureReason];
  157. }
  158. }
  159. if (!responseError) {
  160. NSString *failureReason = @"Invalid fetch response, expected 'token' or 'Error' key";
  161. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenFetchOperationBadResponse, @"%@",
  162. failureReason);
  163. responseError = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeUnknown
  164. failureReason:failureReason];
  165. }
  166. [self finishWithResult:FIRMessagingTokenOperationError 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