You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1187 lines
46 KiB

  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 "FIRInstanceID.h"
  17. #import <FirebaseCore/FIRAppInternal.h>
  18. #import <FirebaseCore/FIRComponent.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIRLibrary.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  23. #import "FIRInstanceID+Private.h"
  24. #import "FIRInstanceIDAuthService.h"
  25. #import "FIRInstanceIDCheckinPreferences.h"
  26. #import "FIRInstanceIDCombinedHandler.h"
  27. #import "FIRInstanceIDConstants.h"
  28. #import "FIRInstanceIDDefines.h"
  29. #import "FIRInstanceIDKeyPairStore.h"
  30. #import "FIRInstanceIDLogger.h"
  31. #import "FIRInstanceIDStore.h"
  32. #import "FIRInstanceIDTokenInfo.h"
  33. #import "FIRInstanceIDTokenManager.h"
  34. #import "FIRInstanceIDUtilities.h"
  35. #import "FIRInstanceIDVersionUtilities.h"
  36. #import "NSError+FIRInstanceID.h"
  37. // Public constants
  38. NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
  39. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  40. const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
  41. @"com.firebase.iid.notif.refresh-token";
  42. #else
  43. NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
  44. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  45. NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
  46. // Private constants
  47. int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60; // 20 minutes
  48. int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10; // 10 seconds
  49. // we retry only a max 5 times.
  50. // TODO(chliangGoogle): If we still fail we should listen for the network change notification
  51. // since GCM would have started Reachability. We only start retrying after we see a configuration
  52. // change.
  53. NSInteger const kMaxRetryCountForDefaultToken = 5;
  54. #if TARGET_OS_IOS || TARGET_OS_TV
  55. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  56. #else
  57. static NSString *const kEntitlementsAPSEnvironmentKey = @"com.apple.developer.aps-environment";
  58. #endif
  59. static NSString *const kEntitlementsKeyForMac = @"Entitlements";
  60. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  61. /// FIRMessaging selector that returns the current FIRMessaging auto init
  62. /// enabled flag.
  63. static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled = @"isAutoInitEnabled";
  64. static NSString *const kFIRInstanceIDFCMSelectorInstance = @"messaging";
  65. static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
  66. static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
  67. @"FIRAppReadyToConfigureSDKNotification";
  68. static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
  69. static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
  70. static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
  71. static NSInteger const kFIRIIDErrorCodeInstanceIDFailed = -121;
  72. typedef void (^FIRInstanceIDKeyPairHandler)(FIRInstanceIDKeyPair *keyPair, NSError *error);
  73. /**
  74. * The APNS token type for the app. If the token type is set to `UNKNOWN`
  75. * InstanceID will implicitly try to figure out what the actual token type
  76. * is from the provisioning profile.
  77. * This must match FIRMessagingAPNSTokenType in FIRMessaging.h
  78. */
  79. typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
  80. /// Unknown token type.
  81. FIRInstanceIDAPNSTokenTypeUnknown,
  82. /// Sandbox token type.
  83. FIRInstanceIDAPNSTokenTypeSandbox,
  84. /// Production token type.
  85. FIRInstanceIDAPNSTokenTypeProd,
  86. } NS_SWIFT_NAME(InstanceIDAPNSTokenType);
  87. @interface FIRInstanceIDResult ()
  88. @property(nonatomic, readwrite, copy) NSString *instanceID;
  89. @property(nonatomic, readwrite, copy) NSString *token;
  90. @end
  91. @interface FIRInstanceID ()
  92. // FIRApp configuration objects.
  93. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  94. @property(nonatomic, readwrite, copy) NSString *firebaseAppID;
  95. // Raw APNS token data
  96. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  97. @property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
  98. // String-based, internal representation of APNS token
  99. @property(nonatomic, readwrite, copy) NSString *APNSTupleString;
  100. // Token fetched from the server automatically for the default app.
  101. @property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
  102. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  103. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPairStore *keyPairStore;
  104. // backoff and retry for default token
  105. @property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
  106. @property(atomic, strong, nullable)
  107. FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
  108. @end
  109. // InstanceID doesn't provide any functionality to other components,
  110. // so it provides a private, empty protocol that it conforms to and use it for registration.
  111. @protocol FIRInstanceIDInstanceProvider
  112. @end
  113. @interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
  114. @end
  115. @implementation FIRInstanceIDResult
  116. - (id)copyWithZone:(NSZone *)zone {
  117. FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
  118. result.instanceID = self.instanceID;
  119. result.token = self.token;
  120. return result;
  121. }
  122. @end
  123. @implementation FIRInstanceID
  124. // File static to support InstanceID tests that call [FIRInstanceID instanceID] after
  125. // [FIRInstanceID instanceIDForTests].
  126. static FIRInstanceID *gInstanceID;
  127. + (instancetype)instanceID {
  128. // If the static instance was created, return it. This should only be set in tests and we should
  129. // eventually use proper dependency injection for a better test structure.
  130. if (gInstanceID != nil) {
  131. return gInstanceID;
  132. }
  133. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  134. FIRInstanceID *instanceID =
  135. (FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
  136. return instanceID;
  137. }
  138. - (instancetype)initPrivately {
  139. self = [super init];
  140. if (self != nil) {
  141. // Use automatic detection of sandbox, unless otherwise set by developer
  142. _apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
  143. }
  144. return self;
  145. }
  146. + (FIRInstanceID *)instanceIDForTests {
  147. gInstanceID = [[FIRInstanceID alloc] initPrivately];
  148. [gInstanceID start];
  149. return gInstanceID;
  150. }
  151. - (void)dealloc {
  152. [[NSNotificationCenter defaultCenter] removeObserver:self];
  153. }
  154. #pragma mark - Tokens
  155. - (NSString *)token {
  156. if (!self.fcmSenderID.length) {
  157. return nil;
  158. }
  159. NSString *cachedToken = [self cachedTokenIfAvailable];
  160. if (cachedToken) {
  161. return cachedToken;
  162. } else {
  163. // If we've never had a cached default token, we should fetch one because unrelatedly,
  164. // this request will help us determine whether the locally-generated Instance ID keypair is not
  165. // unique, and therefore generate a new one.
  166. [self defaultTokenWithHandler:nil];
  167. return nil;
  168. }
  169. }
  170. - (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
  171. FIRInstanceID_WEAKIFY(self);
  172. [self getIDWithHandler:^(NSString *identity, NSError *error) {
  173. FIRInstanceID_STRONGIFY(self);
  174. // This is in main queue already
  175. if (error) {
  176. if (handler) {
  177. handler(nil, error);
  178. }
  179. return;
  180. }
  181. FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
  182. result.instanceID = identity;
  183. NSString *cachedToken = [self cachedTokenIfAvailable];
  184. if (cachedToken) {
  185. if (handler) {
  186. result.token = cachedToken;
  187. handler(result, nil);
  188. }
  189. // If no handler, simply return since client has generated iid and token.
  190. return;
  191. }
  192. [self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
  193. if (handler) {
  194. if (error) {
  195. handler(nil, error);
  196. return;
  197. }
  198. result.token = token;
  199. handler(result, nil);
  200. }
  201. }];
  202. }];
  203. }
  204. - (NSString *)cachedTokenIfAvailable {
  205. FIRInstanceIDTokenInfo *cachedTokenInfo =
  206. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
  207. scope:kFIRInstanceIDDefaultTokenScope];
  208. return cachedTokenInfo.token;
  209. }
  210. - (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
  211. if (_defaultFCMToken && defaultFCMToken && [defaultFCMToken isEqualToString:_defaultFCMToken]) {
  212. return;
  213. }
  214. _defaultFCMToken = defaultFCMToken;
  215. // Sending this notification out will ensure that FIRMessaging has the updated
  216. // default FCM token.
  217. NSNotification *internalDefaultTokenNotification =
  218. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenNotification
  219. object:_defaultFCMToken];
  220. [[NSNotificationQueue defaultQueue] enqueueNotification:internalDefaultTokenNotification
  221. postingStyle:NSPostASAP];
  222. }
  223. - (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
  224. scope:(NSString *)scope
  225. options:(NSDictionary *)options
  226. handler:(FIRInstanceIDTokenHandler)handler {
  227. if (!handler) {
  228. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
  229. kFIRInstanceIDInvalidNilHandlerError);
  230. return;
  231. }
  232. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  233. if (options.count) {
  234. [tokenOptions addEntriesFromDictionary:options];
  235. }
  236. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  237. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  238. if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
  239. // APNS key was given, but server type is missing. Supply the server type with automatic
  240. // checking. This can happen when the token is requested from FCM, which does not include a
  241. // server type during its request.
  242. tokenOptions[serverTypeKey] = @([self isSandboxApp]);
  243. }
  244. // comparing enums to ints directly throws a warning
  245. FIRInstanceIDErrorCode noError = INT_MAX;
  246. FIRInstanceIDErrorCode errorCode = noError;
  247. if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
  248. errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
  249. } else if (FIRInstanceIDIsValidGCMScope(scope) &&
  250. ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
  251. errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
  252. } else if (![authorizedEntity length]) {
  253. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  254. } else if (![scope length]) {
  255. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  256. } else if (!self.keyPairStore) {
  257. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  258. }
  259. FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
  260. dispatch_async(dispatch_get_main_queue(), ^{
  261. handler(token, error);
  262. });
  263. };
  264. if (errorCode != noError) {
  265. newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  266. return;
  267. }
  268. // TODO(chliangGoogle): Add some validation logic that the APNs token data and sandbox value are
  269. // supplied in the valid format (NSData and BOOL, respectively).
  270. // Add internal options
  271. if (self.firebaseAppID) {
  272. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  273. }
  274. FIRInstanceID_WEAKIFY(self);
  275. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  276. [authService
  277. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  278. FIRInstanceID_STRONGIFY(self);
  279. if (error) {
  280. newHandler(nil, error);
  281. return;
  282. }
  283. // Only use the token in the cache if the APNSInfo matches what the request's options has.
  284. // It's possible for the request to be with a newer APNs device token, which should be
  285. // honored.
  286. FIRInstanceIDTokenInfo *cachedTokenInfo =
  287. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  288. if (cachedTokenInfo) {
  289. // Ensure that the cached token matches APNs data before returning it.
  290. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  291. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  292. // If either the APNs info is missing in both, or if they are an exact match, then we can
  293. // use this cached token.
  294. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  295. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  296. newHandler(cachedTokenInfo.token, nil);
  297. return;
  298. }
  299. }
  300. FIRInstanceID_WEAKIFY(self);
  301. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  302. FIRInstanceID_STRONGIFY(self);
  303. if (error) {
  304. NSError *newError =
  305. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  306. newHandler(nil, newError);
  307. } else {
  308. [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  309. scope:[scope copy]
  310. keyPair:keyPair
  311. options:tokenOptions
  312. handler:newHandler];
  313. }
  314. }];
  315. }];
  316. }
  317. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  318. scope:(NSString *)scope
  319. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  320. if (!handler) {
  321. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
  322. kFIRInstanceIDInvalidNilHandlerError);
  323. }
  324. // comparing enums to ints directly throws a warning
  325. FIRInstanceIDErrorCode noError = INT_MAX;
  326. FIRInstanceIDErrorCode errorCode = noError;
  327. if (![authorizedEntity length]) {
  328. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  329. } else if (![scope length]) {
  330. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  331. } else if (!self.keyPairStore) {
  332. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  333. }
  334. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  335. // If a default token is deleted successfully, reset the defaultFCMToken too.
  336. if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
  337. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
  338. self.defaultFCMToken = nil;
  339. }
  340. dispatch_async(dispatch_get_main_queue(), ^{
  341. handler(error);
  342. });
  343. };
  344. if (errorCode != noError) {
  345. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  346. return;
  347. }
  348. FIRInstanceID_WEAKIFY(self);
  349. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  350. [authService
  351. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  352. FIRInstanceID_STRONGIFY(self);
  353. if (error) {
  354. newHandler(error);
  355. return;
  356. }
  357. FIRInstanceID_WEAKIFY(self);
  358. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  359. FIRInstanceID_STRONGIFY(self);
  360. if (error) {
  361. NSError *newError =
  362. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  363. newHandler(newError);
  364. } else {
  365. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  366. scope:scope
  367. keyPair:keyPair
  368. handler:newHandler];
  369. }
  370. }];
  371. }];
  372. }
  373. - (void)asyncLoadKeyPairWithHandler:(FIRInstanceIDKeyPairHandler)handler {
  374. FIRInstanceID_WEAKIFY(self);
  375. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  376. FIRInstanceID_STRONGIFY(self);
  377. NSError *error = nil;
  378. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  379. dispatch_async(dispatch_get_main_queue(), ^{
  380. if (error) {
  381. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID002,
  382. @"Failed to retreieve keyPair %@", error);
  383. if (handler) {
  384. handler(nil, error);
  385. }
  386. } else if (!keyPair && !error) {
  387. if (handler) {
  388. handler(nil,
  389. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair]);
  390. }
  391. } else {
  392. if (handler) {
  393. handler(keyPair, nil);
  394. }
  395. }
  396. });
  397. });
  398. }
  399. #pragma mark - Identity
  400. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  401. if (!handler) {
  402. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
  403. kFIRInstanceIDInvalidNilHandlerError);
  404. return;
  405. }
  406. void (^callHandlerOnMainThread)(NSString *, NSError *) = ^(NSString *identity, NSError *error) {
  407. dispatch_async(dispatch_get_main_queue(), ^{
  408. handler(identity, error);
  409. });
  410. };
  411. if (!self.keyPairStore) {
  412. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidStart];
  413. callHandlerOnMainThread(nil, error);
  414. return;
  415. }
  416. FIRInstanceID_WEAKIFY(self);
  417. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  418. FIRInstanceID_STRONGIFY(self);
  419. NSError *error;
  420. NSString *appIdentity = [self.keyPairStore appIdentityWithError:&error];
  421. // When getID is explicitly called, trigger getToken to make sure token always exists.
  422. // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
  423. if (appIdentity) {
  424. [self token];
  425. }
  426. callHandlerOnMainThread(appIdentity, error);
  427. });
  428. }
  429. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  430. if (!handler) {
  431. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  432. kFIRInstanceIDInvalidNilHandlerError);
  433. return;
  434. }
  435. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  436. if ([NSThread isMainThread]) {
  437. handler(error);
  438. return;
  439. }
  440. dispatch_async(dispatch_get_main_queue(), ^{
  441. handler(error);
  442. });
  443. };
  444. if (!self.keyPairStore) {
  445. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  446. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  447. return;
  448. }
  449. FIRInstanceID_WEAKIFY(self);
  450. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  451. FIRInstanceID_STRONGIFY(self);
  452. if (error) {
  453. callHandlerOnMainThread(error);
  454. return;
  455. }
  456. [self deleteIdentityWithHandler:^(NSError *error) {
  457. callHandlerOnMainThread(error);
  458. }];
  459. };
  460. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  461. FIRInstanceID_STRONGIFY(self);
  462. if (error) {
  463. NSError *newError =
  464. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  465. callHandlerOnMainThread(newError);
  466. } else {
  467. [self.tokenManager deleteAllTokensWithKeyPair:keyPair handler:deleteTokensHandler];
  468. }
  469. }];
  470. }
  471. - (void)notifyIdentityReset {
  472. [self deleteIdentityWithHandler:nil];
  473. }
  474. // Delete all the local cache checkin, IID and token.
  475. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  476. // Delete tokens.
  477. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  478. // Reset FCM token.
  479. self.defaultFCMToken = nil;
  480. if (deleteTokenError) {
  481. if (handler) {
  482. handler(deleteTokenError);
  483. }
  484. return;
  485. }
  486. // Delete Instance ID.
  487. [self.keyPairStore
  488. deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  489. handler:^(NSError *error) {
  490. NSError *deletePlistError;
  491. [self.keyPairStore
  492. removeKeyPairCreationTimePlistWithError:&deletePlistError];
  493. if (error || deletePlistError) {
  494. if (handler) {
  495. // Prefer to use the delete Instance ID error.
  496. error = [NSError
  497. errorWithFIRInstanceIDErrorCode:
  498. kFIRInstanceIDErrorCodeUnknown
  499. userInfo:@{
  500. NSUnderlyingErrorKey : error
  501. ? error
  502. : deletePlistError
  503. }];
  504. handler(error);
  505. }
  506. return;
  507. }
  508. // Delete checkin.
  509. [self.tokenManager.authService
  510. resetCheckinWithHandler:^(NSError *error) {
  511. if (error) {
  512. if (handler) {
  513. handler(error);
  514. }
  515. return;
  516. }
  517. // Only request new token if FCM auto initialization is
  518. // enabled.
  519. if ([self isFCMAutoInitEnabled]) {
  520. // Deletion succeeds! Requesting new checkin, IID and token.
  521. // TODO(chliangGoogle) see if dispatch_after is necessary
  522. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  523. (int64_t)(0.5 * NSEC_PER_SEC)),
  524. dispatch_get_main_queue(), ^{
  525. [self defaultTokenWithHandler:nil];
  526. });
  527. }
  528. if (handler) {
  529. handler(nil);
  530. }
  531. }];
  532. }];
  533. }];
  534. }
  535. #pragma mark - Checkin
  536. - (BOOL)tryToLoadValidCheckinInfo {
  537. FIRInstanceIDCheckinPreferences *checkinPreferences =
  538. [self.tokenManager.authService checkinPreferences];
  539. return [checkinPreferences hasValidCheckinInfo];
  540. }
  541. - (NSString *)deviceAuthID {
  542. return [self.tokenManager.authService checkinPreferences].deviceID;
  543. }
  544. - (NSString *)secretToken {
  545. return [self.tokenManager.authService checkinPreferences].secretToken;
  546. }
  547. - (NSString *)versionInfo {
  548. return [self.tokenManager.authService checkinPreferences].versionInfo;
  549. }
  550. #pragma mark - Config
  551. + (void)load {
  552. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  553. withName:@"fire-iid"
  554. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  555. }
  556. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  557. FIRComponentCreationBlock creationBlock =
  558. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  559. // Ensure it's cached so it returns the same instance every time instanceID is called.
  560. *isCacheable = YES;
  561. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  562. [instanceID start];
  563. return instanceID;
  564. };
  565. FIRComponent *instanceIDProvider =
  566. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  567. instantiationTiming:FIRInstantiationTimingLazy
  568. dependencies:@[]
  569. creationBlock:creationBlock];
  570. return @[ instanceIDProvider ];
  571. }
  572. + (void)configureWithApp:(FIRApp *)app {
  573. if (!app.isDefaultApp) {
  574. // Only configure for the default FIRApp.
  575. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  576. @"Firebase Instance ID only works with the default app.");
  577. return;
  578. }
  579. [[FIRInstanceID instanceID] configureInstanceIDWithOptions:app.options app:app];
  580. }
  581. - (void)configureInstanceIDWithOptions:(FIROptions *)options app:(FIRApp *)firApp {
  582. NSString *GCMSenderID = options.GCMSenderID;
  583. if (!GCMSenderID.length) {
  584. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  585. @"Firebase not set up correctly, nil or empty senderID.");
  586. [FIRInstanceID exitWithReason:@"GCM_SENDER_ID must not be nil or empty." forFirebaseApp:firApp];
  587. return;
  588. }
  589. self.fcmSenderID = GCMSenderID;
  590. self.firebaseAppID = firApp.options.googleAppID;
  591. // FCM generates a FCM token during app start for sending push notification to device.
  592. // This is not needed for app extension.
  593. if (![GULAppEnvironmentUtil isAppExtension]) {
  594. [self didCompleteConfigure];
  595. }
  596. }
  597. + (NSError *)configureErrorWithReason:(nonnull NSString *)reason {
  598. NSString *description =
  599. [NSString stringWithFormat:@"Configuration failed for service %@.", kFIRIIDServiceInstanceID];
  600. if (!reason.length) {
  601. reason = @"Unknown reason";
  602. }
  603. NSDictionary *userInfo =
  604. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  605. return [NSError errorWithDomain:kFIRIIDErrorDomain
  606. code:kFIRIIDErrorCodeInstanceIDFailed
  607. userInfo:userInfo];
  608. }
  609. + (void)exitWithReason:(nonnull NSString *)reason forFirebaseApp:(FIRApp *)firebaseApp {
  610. [NSException raise:kFIRIIDErrorDomain
  611. format:@"Could not configure Firebase InstanceID. %@", reason];
  612. }
  613. // This is used to start any operations when we receive FirebaseSDK setup notification
  614. // from FIRCore.
  615. - (void)didCompleteConfigure {
  616. NSString *cachedToken = [self cachedTokenIfAvailable];
  617. // When there is a cached token, do the token refresh.
  618. if (cachedToken) {
  619. // Clean up expired tokens by checking the token refresh policy.
  620. if ([self.tokenManager checkForTokenRefreshPolicy]) {
  621. // Default token is expired, fetch default token from server.
  622. [self defaultTokenWithHandler:nil];
  623. }
  624. // Notify FCM with the default token.
  625. self.defaultFCMToken = [self token];
  626. } else if ([self isFCMAutoInitEnabled]) {
  627. // When there is no cached token, must check auto init is enabled.
  628. // If it's disabled, don't initiate token generation/refresh.
  629. // If no cache token and auto init is enabled, fetch a token from server.
  630. [self defaultTokenWithHandler:nil];
  631. // Notify FCM with the default token.
  632. self.defaultFCMToken = [self token];
  633. }
  634. // ONLY checkin when auto data collection is turned on.
  635. if ([self isFCMAutoInitEnabled]) {
  636. [self.tokenManager.authService scheduleCheckin:YES];
  637. }
  638. }
  639. - (BOOL)isFCMAutoInitEnabled {
  640. Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
  641. // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
  642. if (!messagingClass) {
  643. return NO;
  644. }
  645. // Messaging doesn't have the singleton method, auto init should be enabled since FCM exists.
  646. SEL instanceSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorInstance);
  647. if (![messagingClass respondsToSelector:instanceSelector]) {
  648. return YES;
  649. }
  650. // Get FIRMessaging shared instance.
  651. IMP messagingInstanceIMP = [messagingClass methodForSelector:instanceSelector];
  652. id (*getMessagingInstance)(id, SEL) = (void *)messagingInstanceIMP;
  653. id messagingInstance = getMessagingInstance(messagingClass, instanceSelector);
  654. // Messaging doesn't have the property, auto init should be enabled since FCM exists.
  655. SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
  656. if (![messagingInstance respondsToSelector:autoInitSelector]) {
  657. return YES;
  658. }
  659. // Get autoInitEnabled method.
  660. IMP isAutoInitEnabledIMP = [messagingInstance methodForSelector:autoInitSelector];
  661. BOOL (*isAutoInitEnabled)(id, SEL) = (BOOL(*)(id, SEL))isAutoInitEnabledIMP;
  662. // Check FCM's isAutoInitEnabled property.
  663. return isAutoInitEnabled(messagingInstance, autoInitSelector);
  664. }
  665. // Actually makes InstanceID instantiate both the IID and Token-related subsystems.
  666. - (void)start {
  667. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  668. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  669. }
  670. [self setupTokenManager];
  671. [self setupKeyPairManager];
  672. [self setupNotificationListeners];
  673. }
  674. // Creates the token manager, which is used for fetching, caching, and retrieving tokens.
  675. - (void)setupTokenManager {
  676. self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
  677. }
  678. // Creates a key pair manager, which stores the public/private keys needed to generate an
  679. // application instance ID.
  680. - (void)setupKeyPairManager {
  681. self.keyPairStore = [[FIRInstanceIDKeyPairStore alloc] init];
  682. if ([self.keyPairStore invalidateKeyPairsIfNeeded]) {
  683. // Reset tokens right away when keypair is deleted, otherwise async call can make first query
  684. // of token happens before reset old tokens during app start.
  685. // TODO(chliangGoogle): Delete all tokens on server too, using
  686. // deleteAllTokensWithKeyPair:handler:. This requires actually retrieving the invalid keypair
  687. // from Keychain, which is something that the key pair store does not currently do.
  688. [self.tokenManager deleteAllTokensLocallyWithHandler:nil];
  689. }
  690. }
  691. - (void)setupNotificationListeners {
  692. // To prevent double notifications remove observer from all events during setup.
  693. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  694. [center removeObserver:self];
  695. [center addObserver:self
  696. selector:@selector(notifyIdentityReset)
  697. name:kFIRInstanceIDIdentityInvalidatedNotification
  698. object:nil];
  699. [center addObserver:self
  700. selector:@selector(notifyAPNSTokenIsSet:)
  701. name:kFIRInstanceIDAPNSTokenNotification
  702. object:nil];
  703. }
  704. #pragma mark - Private Helpers
  705. /// Maximum retry count to fetch the default token.
  706. + (int64_t)maxRetryCountForDefaultToken {
  707. return kMaxRetryCountForDefaultToken;
  708. }
  709. /// Minimum interval in seconds between retries to fetch the default token.
  710. + (int64_t)minIntervalForDefaultTokenRetry {
  711. return kMinRetryIntervalForDefaultTokenInSeconds;
  712. }
  713. /// Maximum retry interval between retries to fetch default token.
  714. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
  715. return kMaxRetryIntervalForDefaultTokenInSeconds;
  716. }
  717. - (NSInteger)retryIntervalToFetchDefaultToken {
  718. if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
  719. return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
  720. }
  721. // exponential backoff with a fixed initial retry time
  722. // 11s, 22s, 44s, 88s ...
  723. int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
  724. return (NSInteger)MIN(
  725. (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
  726. kMaxRetryIntervalForDefaultTokenInSeconds);
  727. }
  728. - (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
  729. [self defaultTokenWithRetry:NO handler:aHandler];
  730. }
  731. /**
  732. * @param retry Indicates if the method is called to perform a retry after a failed attempt.
  733. * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
  734. * nil`
  735. */
  736. - (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
  737. BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
  738. if (!self.defaultTokenFetchHandler) {
  739. self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
  740. }
  741. if (aHandler) {
  742. [self.defaultTokenFetchHandler addHandler:aHandler];
  743. }
  744. if (!shouldPerformRequest) {
  745. return;
  746. }
  747. NSDictionary *instanceIDOptions = @{};
  748. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  749. if (hasFirebaseMessaging && self.apnsTokenData) {
  750. BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
  751. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  752. isSandboxApp = [self isSandboxApp];
  753. }
  754. instanceIDOptions = @{
  755. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  756. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
  757. };
  758. }
  759. FIRInstanceID_WEAKIFY(self);
  760. FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
  761. FIRInstanceID_STRONGIFY(self);
  762. if (error) {
  763. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
  764. @"Failed to fetch default token %@", error);
  765. // This notification can be sent multiple times since we can't guarantee success at any point
  766. // of time.
  767. NSNotification *tokenFetchFailNotification =
  768. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
  769. object:[error copy]];
  770. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
  771. postingStyle:NSPostASAP];
  772. self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
  773. [[self class] maxRetryCountForDefaultToken]);
  774. // Do not retry beyond the maximum limit.
  775. if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
  776. NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
  777. [self retryGetDefaultTokenAfter:retryInterval];
  778. } else {
  779. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
  780. @"Failed to retrieve the default FCM token after %ld retries",
  781. (long)self.retryCountForDefaultToken);
  782. [self performDefaultTokenHandlerWithToken:nil error:error];
  783. }
  784. } else {
  785. // If somebody updated IID with APNS token while our initial request did not have it
  786. // set we need to update it on the server.
  787. NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
  788. BOOL isSandboxInRequest =
  789. [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
  790. // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
  791. NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  792. deviceTokenInRequest, isSandboxInRequest);
  793. // If the APNs value either remained nil, or was the same non-nil value, the APNs value
  794. // did not change.
  795. BOOL APNSRemainedSameDuringFetch =
  796. (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
  797. ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
  798. if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
  799. // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
  800. // value.
  801. [self retryGetDefaultTokenAfter:0];
  802. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
  803. @"Received APNS token while fetching default token. "
  804. @"Refetching default token.");
  805. // Do not notify and handle completion handler since this is a retry.
  806. // Simply return.
  807. return;
  808. } else {
  809. FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
  810. @"Successfully fetched default token.");
  811. }
  812. // Post the required notifications if somebody is waiting.
  813. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
  814. token);
  815. NSString *previousFCMToken = self.defaultFCMToken;
  816. self.defaultFCMToken = token;
  817. // Only notify of token refresh if we have a new valid token that's different than before
  818. if (self.defaultFCMToken.length && ![self.defaultFCMToken isEqualToString:previousFCMToken]) {
  819. NSNotification *tokenRefreshNotification =
  820. [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
  821. object:[self.defaultFCMToken copy]];
  822. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
  823. postingStyle:NSPostASAP];
  824. }
  825. [self performDefaultTokenHandlerWithToken:token error:nil];
  826. }
  827. };
  828. [self tokenWithAuthorizedEntity:self.fcmSenderID
  829. scope:kFIRInstanceIDDefaultTokenScope
  830. options:instanceIDOptions
  831. handler:newHandler];
  832. }
  833. /**
  834. *
  835. */
  836. - (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
  837. if (!self.defaultTokenFetchHandler) {
  838. return;
  839. }
  840. [self.defaultTokenFetchHandler combinedHandler](token, error);
  841. self.defaultTokenFetchHandler = nil;
  842. }
  843. - (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
  844. FIRInstanceID_WEAKIFY(self);
  845. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
  846. dispatch_get_main_queue(), ^{
  847. FIRInstanceID_STRONGIFY(self);
  848. // Pass nil: no new handlers to be added, currently existing handlers
  849. // will be called
  850. [self defaultTokenWithRetry:YES handler:nil];
  851. });
  852. }
  853. #pragma mark - APNS Token
  854. // This should only be triggered from FCM.
  855. - (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
  856. NSData *token = notification.object;
  857. if (!token || ![token isKindOfClass:[NSData class]]) {
  858. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
  859. NSStringFromClass([notification.object class]));
  860. return;
  861. }
  862. NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
  863. // The APNS token is being added, or has changed (rare)
  864. if ([self.apnsTokenData isEqualToData:token]) {
  865. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
  866. @"Trying to reset APNS token to the same value. Will return");
  867. return;
  868. }
  869. // Use this token type for when we have to automatically fetch tokens in the future
  870. self.apnsTokenType = type;
  871. BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
  872. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  873. isSandboxApp = [self isSandboxApp];
  874. }
  875. self.apnsTokenData = [token copy];
  876. self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
  877. // Pro-actively invalidate the default token, if the APNs change makes it
  878. // invalid. Previously, we invalidated just before fetching the token.
  879. NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
  880. [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
  881. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  882. // they are up-to-date.
  883. if (invalidatedTokens.count > 0) {
  884. FIRInstanceID_WEAKIFY(self);
  885. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  886. FIRInstanceID_STRONGIFY(self);
  887. NSMutableDictionary *tokenOptions = [@{
  888. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  889. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  890. } mutableCopy];
  891. if (self.firebaseAppID) {
  892. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  893. }
  894. for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
  895. if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
  896. // We will perform a special fetch for the default FCM token, so that the delegate methods
  897. // are called. For all others, we will do an internal re-fetch.
  898. [self defaultTokenWithHandler:nil];
  899. } else {
  900. [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  901. scope:tokenInfo.scope
  902. keyPair:keyPair
  903. options:tokenOptions
  904. handler:^(NSString *_Nullable token,
  905. NSError *_Nullable error){
  906. }];
  907. }
  908. }
  909. }];
  910. }
  911. }
  912. - (BOOL)isSandboxApp {
  913. static BOOL isSandboxApp = YES;
  914. static dispatch_once_t onceToken;
  915. dispatch_once(&onceToken, ^{
  916. isSandboxApp = ![self isProductionApp];
  917. });
  918. return isSandboxApp;
  919. }
  920. - (BOOL)isProductionApp {
  921. const BOOL defaultAppTypeProd = YES;
  922. NSError *error = nil;
  923. if ([GULAppEnvironmentUtil isSimulator]) {
  924. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  925. @"Use prod profile by default."];
  926. return defaultAppTypeProd;
  927. }
  928. if ([GULAppEnvironmentUtil isFromAppStore]) {
  929. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  930. return defaultAppTypeProd;
  931. }
  932. #if TARGET_OS_IOS || TARGET_OS_TV
  933. NSString *path = [[[NSBundle mainBundle] bundlePath]
  934. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  935. #elif TARGET_OS_OSX
  936. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  937. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  938. #endif
  939. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  940. // Distributed via TestFlight
  941. return defaultAppTypeProd;
  942. }
  943. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  944. if (!profileData.length || error) {
  945. NSString *errorString =
  946. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  947. [self logAPNSConfigurationError:errorString];
  948. return defaultAppTypeProd;
  949. }
  950. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  951. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  952. // ASCII. Replace any 0s or invalid characters in the input.
  953. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  954. for (int i = 0; i < profileData.length; i++) {
  955. uint8_t currentByte = profileBytes[i];
  956. if (!currentByte || currentByte > 127) {
  957. profileBytes[i] = '.';
  958. }
  959. }
  960. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  961. length:profileData.length
  962. encoding:NSASCIIStringEncoding
  963. freeWhenDone:NO];
  964. if (error || !embeddedProfile.length) {
  965. NSString *errorString =
  966. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  967. [self logAPNSConfigurationError:errorString];
  968. return defaultAppTypeProd;
  969. }
  970. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  971. NSString *plistContents;
  972. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  973. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  974. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  975. }
  976. }
  977. if (!plistContents.length) {
  978. return defaultAppTypeProd;
  979. }
  980. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  981. if (!data.length) {
  982. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  983. return defaultAppTypeProd;
  984. }
  985. NSError *plistMapError;
  986. id plistData = [NSPropertyListSerialization propertyListWithData:data
  987. options:NSPropertyListImmutable
  988. format:nil
  989. error:&plistMapError];
  990. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  991. NSString *errorString =
  992. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  993. plistMapError.localizedDescription];
  994. [self logAPNSConfigurationError:errorString];
  995. return defaultAppTypeProd;
  996. }
  997. NSDictionary *plistMap = (NSDictionary *)plistData;
  998. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  999. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  1000. @"Provisioning profile has specifically provisioned devices, "
  1001. @"most likely a Dev profile.");
  1002. }
  1003. #if TARGET_OS_IOS || TARGET_OS_TV
  1004. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  1005. #elif TARGET_OS_OSX
  1006. NSDictionary *entitlements = [plistMap valueForKey:kEntitlementsKeyForMac];
  1007. NSString *apsEnvironment = [entitlements valueForKey:kEntitlementsAPSEnvironmentKey];
  1008. #endif
  1009. NSString *debugString __unused =
  1010. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  1011. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  1012. // No aps-environment in the profile.
  1013. if (!apsEnvironment.length) {
  1014. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  1015. @"correctly configured. Please recheck your provisioning "
  1016. @"profiles. If testing on a simulator this is fine since APNS "
  1017. @"doesn't work on the simulator."];
  1018. return defaultAppTypeProd;
  1019. }
  1020. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  1021. return NO;
  1022. }
  1023. return defaultAppTypeProd;
  1024. }
  1025. /// Log error messages only when Messaging exists in the pod.
  1026. - (void)logAPNSConfigurationError:(NSString *)errorString {
  1027. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  1028. if (hasFirebaseMessaging) {
  1029. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  1030. } else {
  1031. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  1032. }
  1033. }
  1034. @end