FIRAuthAPNSTokenManager.m 8.7 KB

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