暂无描述

FIRAuthAPNSTokenManager.m 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright 2017 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 "FIRAuthAPNSTokenManager.h"
  17. #import <FirebaseCore/FIRLogger.h>
  18. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  19. #import "FIRAuthAPNSToken.h"
  20. #import "FIRAuthGlobalWorkQueue.h"
  21. NS_ASSUME_NONNULL_BEGIN
  22. /** @var kRegistrationTimeout
  23. @brief Timeout for registration for remote notification.
  24. @remarks Once we start to handle `application:didFailToRegisterForRemoteNotificationsWithError:`
  25. we probably don't have to use timeout at all.
  26. */
  27. static const NSTimeInterval kRegistrationTimeout = 5;
  28. /** @var kLegacyRegistrationTimeout
  29. @brief Timeout for registration for remote notification on iOS 7.
  30. */
  31. static const NSTimeInterval kLegacyRegistrationTimeout = 30;
  32. @implementation FIRAuthAPNSTokenManager {
  33. /** @var _application
  34. @brief The @c UIApplication to request the token from.
  35. */
  36. UIApplication *_application;
  37. /** @var _pendingCallbacks
  38. @brief The list of all pending callbacks for the APNs token.
  39. */
  40. NSMutableArray<FIRAuthAPNSTokenCallback> *_pendingCallbacks;
  41. }
  42. - (instancetype)initWithApplication:(UIApplication *)application {
  43. self = [super init];
  44. if (self) {
  45. _application = application;
  46. _timeout = [_application respondsToSelector:@selector(registerForRemoteNotifications)] ?
  47. kRegistrationTimeout : kLegacyRegistrationTimeout;
  48. }
  49. return self;
  50. }
  51. - (void)getTokenWithCallback:(FIRAuthAPNSTokenCallback)callback {
  52. if (_token) {
  53. callback(_token, nil);
  54. return;
  55. }
  56. if (_pendingCallbacks) {
  57. [_pendingCallbacks addObject:callback];
  58. return;
  59. }
  60. _pendingCallbacks =
  61. [[NSMutableArray<FIRAuthAPNSTokenCallback> alloc] initWithObjects:callback, nil];
  62. dispatch_async(dispatch_get_main_queue(), ^{
  63. if ([self->_application respondsToSelector:@selector(registerForRemoteNotifications)]) {
  64. [self->_application registerForRemoteNotifications];
  65. } else {
  66. #pragma clang diagnostic push
  67. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  68. #if TARGET_OS_IOS
  69. [self->_application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
  70. #endif // TARGET_OS_IOS
  71. #pragma clang diagnostic pop
  72. }
  73. });
  74. NSArray<FIRAuthAPNSTokenCallback> *applicableCallbacks = _pendingCallbacks;
  75. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_timeout * NSEC_PER_SEC)),
  76. FIRAuthGlobalWorkQueue(), ^{
  77. // Only cancel if the pending callbacks remain the same, i.e., not triggered yet.
  78. if (applicableCallbacks == self->_pendingCallbacks) {
  79. [self callBackWithToken:nil error:nil];
  80. }
  81. });
  82. }
  83. - (void)setToken:(nullable FIRAuthAPNSToken *)token {
  84. if (!token) {
  85. _token = nil;
  86. return;
  87. }
  88. if (token.type == FIRAuthAPNSTokenTypeUnknown) {
  89. static FIRAuthAPNSTokenType detectedTokenType = FIRAuthAPNSTokenTypeUnknown;
  90. if (detectedTokenType == FIRAuthAPNSTokenTypeUnknown) {
  91. detectedTokenType =
  92. [[self class] isProductionApp] ? FIRAuthAPNSTokenTypeProd : FIRAuthAPNSTokenTypeSandbox;
  93. }
  94. token = [[FIRAuthAPNSToken alloc] initWithData:token.data type:detectedTokenType];
  95. }
  96. _token = token;
  97. [self callBackWithToken:token error:nil];
  98. }
  99. - (void)cancelWithError:(NSError *)error {
  100. [self callBackWithToken:nil error:error];
  101. }
  102. #pragma mark - Internal methods
  103. /** @fn callBack
  104. @brief Calls back all pending callbacks with APNs token or error.
  105. @param token The APNs token if one is available.
  106. @param error The error occurred, if any.
  107. */
  108. - (void)callBackWithToken:(nullable FIRAuthAPNSToken *)token error:(nullable NSError *)error {
  109. if (!_pendingCallbacks) {
  110. return;
  111. }
  112. NSArray<FIRAuthAPNSTokenCallback> *allCallbacks = _pendingCallbacks;
  113. _pendingCallbacks = nil;
  114. for (FIRAuthAPNSTokenCallback callback in allCallbacks) {
  115. callback(token, error);
  116. }
  117. };
  118. /** @fn isProductionApp
  119. @brief Whether or not the app has production (versus sandbox) provisioning profile.
  120. @remarks This method is adapted from @c FIRInstanceID .
  121. */
  122. + (BOOL)isProductionApp {
  123. const BOOL defaultAppTypeProd = YES;
  124. NSError *error = nil;
  125. if ([GULAppEnvironmentUtil isSimulator]) {
  126. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000006", @"Assuming prod APNs token type on simulator.");
  127. return defaultAppTypeProd;
  128. }
  129. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  130. if ([GULAppEnvironmentUtil isFromAppStore]) {
  131. return defaultAppTypeProd;
  132. }
  133. NSString *path = [[[NSBundle mainBundle] bundlePath]
  134. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  135. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  136. // Distributed via TestFlight
  137. return defaultAppTypeProd;
  138. }
  139. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  140. if (!profileData.length || error) {
  141. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000007",
  142. @"Error while reading embedded mobileprovision %@", error);
  143. return defaultAppTypeProd;
  144. }
  145. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  146. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  147. // ASCII. Replace any 0s or invalid characters in the input.
  148. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  149. for (int i = 0; i < profileData.length; i++) {
  150. uint8_t currentByte = profileBytes[i];
  151. if (!currentByte || currentByte > 127) {
  152. profileBytes[i] = '.';
  153. }
  154. }
  155. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  156. length:profileData.length
  157. encoding:NSASCIIStringEncoding
  158. freeWhenDone:NO];
  159. if (error || !embeddedProfile.length) {
  160. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000008",
  161. @"Error while reading embedded mobileprovision %@", error);
  162. return defaultAppTypeProd;
  163. }
  164. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  165. NSString *plistContents;
  166. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  167. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  168. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  169. }
  170. }
  171. if (!plistContents.length) {
  172. return defaultAppTypeProd;
  173. }
  174. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  175. if (!data.length) {
  176. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000009",
  177. @"Couldn't read plist fetched from embedded mobileprovision");
  178. return defaultAppTypeProd;
  179. }
  180. NSError *plistMapError;
  181. id plistData = [NSPropertyListSerialization propertyListWithData:data
  182. options:NSPropertyListImmutable
  183. format:nil
  184. error:&plistMapError];
  185. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  186. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000010",
  187. @"Error while converting assumed plist to dict %@",
  188. plistMapError.localizedDescription);
  189. return defaultAppTypeProd;
  190. }
  191. NSDictionary *plistMap = (NSDictionary *)plistData;
  192. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  193. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000011",
  194. @"Provisioning profile has specifically provisioned devices, "
  195. @"most likely a Dev profile.");
  196. }
  197. NSString *apsEnvironment = [plistMap valueForKeyPath:@"Entitlements.aps-environment"];
  198. FIRLogDebug(kFIRLoggerAuth, @"I-AUT000012",
  199. @"APNS Environment in profile: %@", apsEnvironment);
  200. // No aps-environment in the profile.
  201. if (!apsEnvironment.length) {
  202. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000013",
  203. @"No aps-environment set. If testing on a device APNS is not "
  204. @"correctly configured. Please recheck your provisioning profiles.");
  205. return defaultAppTypeProd;
  206. }
  207. if ([apsEnvironment isEqualToString:@"development"]) {
  208. return NO;
  209. }
  210. return defaultAppTypeProd;
  211. }
  212. @end
  213. NS_ASSUME_NONNULL_END