FIRAuthAPNSTokenManager.m 8.8 KB

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