FIRInstanceID.m 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  55. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  56. /// FIRMessaging selector that returns the current FIRMessaging auto init
  57. /// enabled flag.
  58. static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled = @"isAutoInitEnabled";
  59. static NSString *const kFIRInstanceIDFCMSelectorInstance = @"messaging";
  60. static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
  61. static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
  62. @"FIRAppReadyToConfigureSDKNotification";
  63. static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
  64. static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
  65. static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
  66. static NSInteger const kFIRIIDErrorCodeInstanceIDFailed = -121;
  67. typedef void (^FIRInstanceIDKeyPairHandler)(FIRInstanceIDKeyPair *keyPair, NSError *error);
  68. /**
  69. * The APNS token type for the app. If the token type is set to `UNKNOWN`
  70. * InstanceID will implicitly try to figure out what the actual token type
  71. * is from the provisioning profile.
  72. * This must match FIRMessagingAPNSTokenType in FIRMessaging.h
  73. */
  74. typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
  75. /// Unknown token type.
  76. FIRInstanceIDAPNSTokenTypeUnknown,
  77. /// Sandbox token type.
  78. FIRInstanceIDAPNSTokenTypeSandbox,
  79. /// Production token type.
  80. FIRInstanceIDAPNSTokenTypeProd,
  81. } NS_SWIFT_NAME(InstanceIDAPNSTokenType);
  82. @interface FIRInstanceIDResult ()
  83. @property(nonatomic, readwrite, copy) NSString *instanceID;
  84. @property(nonatomic, readwrite, copy) NSString *token;
  85. @end
  86. @interface FIRInstanceID ()
  87. // FIRApp configuration objects.
  88. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  89. @property(nonatomic, readwrite, copy) NSString *firebaseAppID;
  90. // Raw APNS token data
  91. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  92. @property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
  93. // String-based, internal representation of APNS token
  94. @property(nonatomic, readwrite, copy) NSString *APNSTupleString;
  95. // Token fetched from the server automatically for the default app.
  96. @property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
  97. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  98. @property(nonatomic, readwrite, strong) FIRInstanceIDKeyPairStore *keyPairStore;
  99. // backoff and retry for default token
  100. @property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
  101. @property(atomic, strong, nullable)
  102. FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
  103. @end
  104. // InstanceID doesn't provide any functionality to other components,
  105. // so it provides a private, empty protocol that it conforms to and use it for registration.
  106. @protocol FIRInstanceIDInstanceProvider
  107. @end
  108. @interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
  109. @end
  110. @implementation FIRInstanceIDResult
  111. - (id)copyWithZone:(NSZone *)zone {
  112. FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
  113. result.instanceID = self.instanceID;
  114. result.token = self.token;
  115. return result;
  116. }
  117. @end
  118. @implementation FIRInstanceID
  119. // File static to support InstanceID tests that call [FIRInstanceID instanceID] after
  120. // [FIRInstanceID instanceIDForTests].
  121. static FIRInstanceID *gInstanceID;
  122. + (instancetype)instanceID {
  123. // If the static instance was created, return it. This should only be set in tests and we should
  124. // eventually use proper dependency injection for a better test structure.
  125. if (gInstanceID != nil) {
  126. return gInstanceID;
  127. }
  128. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  129. FIRInstanceID *instanceID =
  130. (FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
  131. return instanceID;
  132. }
  133. - (instancetype)initPrivately {
  134. self = [super init];
  135. if (self != nil) {
  136. // Use automatic detection of sandbox, unless otherwise set by developer
  137. _apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
  138. }
  139. return self;
  140. }
  141. + (FIRInstanceID *)instanceIDForTests {
  142. gInstanceID = [[FIRInstanceID alloc] initPrivately];
  143. [gInstanceID start];
  144. return gInstanceID;
  145. }
  146. - (void)dealloc {
  147. [[NSNotificationCenter defaultCenter] removeObserver:self];
  148. }
  149. #pragma mark - Tokens
  150. - (NSString *)token {
  151. if (!self.fcmSenderID.length) {
  152. return nil;
  153. }
  154. NSString *cachedToken = [self cachedTokenIfAvailable];
  155. if (cachedToken) {
  156. return cachedToken;
  157. } else {
  158. // If we've never had a cached default token, we should fetch one because unrelatedly,
  159. // this request will help us determine whether the locally-generated Instance ID keypair is not
  160. // unique, and therefore generate a new one.
  161. [self defaultTokenWithHandler:nil];
  162. return nil;
  163. }
  164. }
  165. - (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
  166. FIRInstanceID_WEAKIFY(self);
  167. [self getIDWithHandler:^(NSString *identity, NSError *error) {
  168. FIRInstanceID_STRONGIFY(self);
  169. // This is in main queue already
  170. if (error) {
  171. if (handler) {
  172. handler(nil, error);
  173. }
  174. return;
  175. }
  176. FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
  177. result.instanceID = identity;
  178. NSString *cachedToken = [self cachedTokenIfAvailable];
  179. if (cachedToken) {
  180. if (handler) {
  181. result.token = cachedToken;
  182. handler(result, nil);
  183. }
  184. // If no handler, simply return since client has generated iid and token.
  185. return;
  186. }
  187. [self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
  188. if (handler) {
  189. if (error) {
  190. handler(nil, error);
  191. return;
  192. }
  193. result.token = token;
  194. handler(result, nil);
  195. }
  196. }];
  197. }];
  198. }
  199. - (NSString *)cachedTokenIfAvailable {
  200. FIRInstanceIDTokenInfo *cachedTokenInfo =
  201. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
  202. scope:kFIRInstanceIDDefaultTokenScope];
  203. return cachedTokenInfo.token;
  204. }
  205. - (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
  206. if (_defaultFCMToken && defaultFCMToken && [defaultFCMToken isEqualToString:_defaultFCMToken]) {
  207. return;
  208. }
  209. _defaultFCMToken = defaultFCMToken;
  210. // Sending this notification out will ensure that FIRMessaging has the updated
  211. // default FCM token.
  212. NSNotification *internalDefaultTokenNotification =
  213. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenNotification
  214. object:_defaultFCMToken];
  215. [[NSNotificationQueue defaultQueue] enqueueNotification:internalDefaultTokenNotification
  216. postingStyle:NSPostASAP];
  217. }
  218. - (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
  219. scope:(NSString *)scope
  220. options:(NSDictionary *)options
  221. handler:(FIRInstanceIDTokenHandler)handler {
  222. if (!handler) {
  223. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
  224. kFIRInstanceIDInvalidNilHandlerError);
  225. return;
  226. }
  227. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  228. if (options.count) {
  229. [tokenOptions addEntriesFromDictionary:options];
  230. }
  231. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  232. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  233. if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
  234. // APNS key was given, but server type is missing. Supply the server type with automatic
  235. // checking. This can happen when the token is requested from FCM, which does not include a
  236. // server type during its request.
  237. tokenOptions[serverTypeKey] = @([self isSandboxApp]);
  238. }
  239. // comparing enums to ints directly throws a warning
  240. FIRInstanceIDErrorCode noError = INT_MAX;
  241. FIRInstanceIDErrorCode errorCode = noError;
  242. if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
  243. errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
  244. } else if (FIRInstanceIDIsValidGCMScope(scope) &&
  245. ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
  246. errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
  247. } else if (![authorizedEntity length]) {
  248. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  249. } else if (![scope length]) {
  250. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  251. } else if (!self.keyPairStore) {
  252. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  253. }
  254. FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
  255. dispatch_async(dispatch_get_main_queue(), ^{
  256. handler(token, error);
  257. });
  258. };
  259. if (errorCode != noError) {
  260. newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  261. return;
  262. }
  263. // TODO(chliangGoogle): Add some validation logic that the APNs token data and sandbox value are
  264. // supplied in the valid format (NSData and BOOL, respectively).
  265. // Add internal options
  266. if (self.firebaseAppID) {
  267. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  268. }
  269. FIRInstanceID_WEAKIFY(self);
  270. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  271. [authService
  272. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  273. FIRInstanceID_STRONGIFY(self);
  274. if (error) {
  275. newHandler(nil, error);
  276. return;
  277. }
  278. // Only use the token in the cache if the APNSInfo matches what the request's options has.
  279. // It's possible for the request to be with a newer APNs device token, which should be
  280. // honored.
  281. FIRInstanceIDTokenInfo *cachedTokenInfo =
  282. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  283. if (cachedTokenInfo) {
  284. // Ensure that the cached token matches APNs data before returning it.
  285. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  286. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  287. // If either the APNs info is missing in both, or if they are an exact match, then we can
  288. // use this cached token.
  289. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  290. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  291. newHandler(cachedTokenInfo.token, nil);
  292. return;
  293. }
  294. }
  295. FIRInstanceID_WEAKIFY(self);
  296. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  297. FIRInstanceID_STRONGIFY(self);
  298. if (error) {
  299. NSError *newError =
  300. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  301. newHandler(nil, newError);
  302. } else {
  303. [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  304. scope:[scope copy]
  305. keyPair:keyPair
  306. options:tokenOptions
  307. handler:newHandler];
  308. }
  309. }];
  310. }];
  311. }
  312. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  313. scope:(NSString *)scope
  314. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  315. if (!handler) {
  316. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
  317. kFIRInstanceIDInvalidNilHandlerError);
  318. }
  319. // comparing enums to ints directly throws a warning
  320. FIRInstanceIDErrorCode noError = INT_MAX;
  321. FIRInstanceIDErrorCode errorCode = noError;
  322. if (![authorizedEntity length]) {
  323. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  324. } else if (![scope length]) {
  325. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  326. } else if (!self.keyPairStore) {
  327. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  328. }
  329. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  330. // If a default token is deleted successfully, reset the defaultFCMToken too.
  331. if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
  332. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
  333. self.defaultFCMToken = nil;
  334. }
  335. dispatch_async(dispatch_get_main_queue(), ^{
  336. handler(error);
  337. });
  338. };
  339. if (errorCode != noError) {
  340. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  341. return;
  342. }
  343. FIRInstanceID_WEAKIFY(self);
  344. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  345. [authService
  346. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  347. FIRInstanceID_STRONGIFY(self);
  348. if (error) {
  349. newHandler(error);
  350. return;
  351. }
  352. FIRInstanceID_WEAKIFY(self);
  353. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  354. FIRInstanceID_STRONGIFY(self);
  355. if (error) {
  356. NSError *newError =
  357. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  358. newHandler(newError);
  359. } else {
  360. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  361. scope:scope
  362. keyPair:keyPair
  363. handler:newHandler];
  364. }
  365. }];
  366. }];
  367. }
  368. - (void)asyncLoadKeyPairWithHandler:(FIRInstanceIDKeyPairHandler)handler {
  369. FIRInstanceID_WEAKIFY(self);
  370. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  371. FIRInstanceID_STRONGIFY(self);
  372. NSError *error = nil;
  373. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  374. dispatch_async(dispatch_get_main_queue(), ^{
  375. if (error) {
  376. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID002,
  377. @"Failed to retreieve keyPair %@", error);
  378. if (handler) {
  379. handler(nil, error);
  380. }
  381. } else if (!keyPair && !error) {
  382. if (handler) {
  383. handler(nil,
  384. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair]);
  385. }
  386. } else {
  387. if (handler) {
  388. handler(keyPair, nil);
  389. }
  390. }
  391. });
  392. });
  393. }
  394. #pragma mark - Identity
  395. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  396. if (!handler) {
  397. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
  398. kFIRInstanceIDInvalidNilHandlerError);
  399. return;
  400. }
  401. void (^callHandlerOnMainThread)(NSString *, NSError *) = ^(NSString *identity, NSError *error) {
  402. dispatch_async(dispatch_get_main_queue(), ^{
  403. handler(identity, error);
  404. });
  405. };
  406. if (!self.keyPairStore) {
  407. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidStart];
  408. callHandlerOnMainThread(nil, error);
  409. return;
  410. }
  411. FIRInstanceID_WEAKIFY(self);
  412. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  413. FIRInstanceID_STRONGIFY(self);
  414. NSError *error;
  415. NSString *appIdentity = [self.keyPairStore appIdentityWithError:&error];
  416. // When getID is explicitly called, trigger getToken to make sure token always exists.
  417. // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
  418. if (appIdentity) {
  419. [self token];
  420. }
  421. callHandlerOnMainThread(appIdentity, error);
  422. });
  423. }
  424. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  425. if (!handler) {
  426. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  427. kFIRInstanceIDInvalidNilHandlerError);
  428. return;
  429. }
  430. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  431. if ([NSThread isMainThread]) {
  432. handler(error);
  433. return;
  434. }
  435. dispatch_async(dispatch_get_main_queue(), ^{
  436. handler(error);
  437. });
  438. };
  439. if (!self.keyPairStore) {
  440. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  441. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  442. return;
  443. }
  444. FIRInstanceID_WEAKIFY(self);
  445. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  446. FIRInstanceID_STRONGIFY(self);
  447. if (error) {
  448. callHandlerOnMainThread(error);
  449. return;
  450. }
  451. [self deleteIdentityWithHandler:^(NSError *error) {
  452. callHandlerOnMainThread(error);
  453. }];
  454. };
  455. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  456. FIRInstanceID_STRONGIFY(self);
  457. if (error) {
  458. NSError *newError =
  459. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  460. callHandlerOnMainThread(newError);
  461. } else {
  462. [self.tokenManager deleteAllTokensWithKeyPair:keyPair handler:deleteTokensHandler];
  463. }
  464. }];
  465. }
  466. - (void)notifyIdentityReset {
  467. [self deleteIdentityWithHandler:nil];
  468. }
  469. // Delete all the local cache checkin, IID and token.
  470. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  471. // Delete tokens.
  472. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  473. // Reset FCM token.
  474. self.defaultFCMToken = nil;
  475. if (deleteTokenError) {
  476. if (handler) {
  477. handler(deleteTokenError);
  478. }
  479. return;
  480. }
  481. // Delete Instance ID.
  482. [self.keyPairStore
  483. deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  484. handler:^(NSError *error) {
  485. NSError *deletePlistError;
  486. [self.keyPairStore
  487. removeKeyPairCreationTimePlistWithError:&deletePlistError];
  488. if (error || deletePlistError) {
  489. if (handler) {
  490. // Prefer to use the delete Instance ID error.
  491. error = [NSError
  492. errorWithFIRInstanceIDErrorCode:
  493. kFIRInstanceIDErrorCodeUnknown
  494. userInfo:@{
  495. NSUnderlyingErrorKey : error
  496. ? error
  497. : deletePlistError
  498. }];
  499. handler(error);
  500. }
  501. return;
  502. }
  503. // Delete checkin.
  504. [self.tokenManager.authService
  505. resetCheckinWithHandler:^(NSError *error) {
  506. if (error) {
  507. if (handler) {
  508. handler(error);
  509. }
  510. return;
  511. }
  512. // Only request new token if FCM auto initialization is
  513. // enabled.
  514. if ([self isFCMAutoInitEnabled]) {
  515. // Deletion succeeds! Requesting new checkin, IID and token.
  516. // TODO(chliangGoogle) see if dispatch_after is necessary
  517. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  518. (int64_t)(0.5 * NSEC_PER_SEC)),
  519. dispatch_get_main_queue(), ^{
  520. [self defaultTokenWithHandler:nil];
  521. });
  522. }
  523. if (handler) {
  524. handler(nil);
  525. }
  526. }];
  527. }];
  528. }];
  529. }
  530. #pragma mark - Checkin
  531. - (BOOL)tryToLoadValidCheckinInfo {
  532. FIRInstanceIDCheckinPreferences *checkinPreferences =
  533. [self.tokenManager.authService checkinPreferences];
  534. return [checkinPreferences hasValidCheckinInfo];
  535. }
  536. - (NSString *)deviceAuthID {
  537. return [self.tokenManager.authService checkinPreferences].deviceID;
  538. }
  539. - (NSString *)secretToken {
  540. return [self.tokenManager.authService checkinPreferences].secretToken;
  541. }
  542. - (NSString *)versionInfo {
  543. return [self.tokenManager.authService checkinPreferences].versionInfo;
  544. }
  545. #pragma mark - Config
  546. + (void)load {
  547. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  548. withName:@"fire-iid"
  549. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  550. }
  551. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  552. FIRComponentCreationBlock creationBlock =
  553. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  554. // Ensure it's cached so it returns the same instance every time instanceID is called.
  555. *isCacheable = YES;
  556. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  557. [instanceID start];
  558. return instanceID;
  559. };
  560. FIRComponent *instanceIDProvider =
  561. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  562. instantiationTiming:FIRInstantiationTimingLazy
  563. dependencies:@[]
  564. creationBlock:creationBlock];
  565. return @[ instanceIDProvider ];
  566. }
  567. + (void)configureWithApp:(FIRApp *)app {
  568. if (!app.isDefaultApp) {
  569. // Only configure for the default FIRApp.
  570. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  571. @"Firebase Instance ID only works with the default app.");
  572. return;
  573. }
  574. [[FIRInstanceID instanceID] configureInstanceIDWithOptions:app.options app:app];
  575. }
  576. - (void)configureInstanceIDWithOptions:(FIROptions *)options app:(FIRApp *)firApp {
  577. NSString *GCMSenderID = options.GCMSenderID;
  578. if (!GCMSenderID.length) {
  579. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  580. @"Firebase not set up correctly, nil or empty senderID.");
  581. [FIRInstanceID exitWithReason:@"GCM_SENDER_ID must not be nil or empty." forFirebaseApp:firApp];
  582. return;
  583. }
  584. self.fcmSenderID = GCMSenderID;
  585. self.firebaseAppID = firApp.options.googleAppID;
  586. // FCM generates a FCM token during app start for sending push notification to device.
  587. // This is not needed for app extension.
  588. if (![GULAppEnvironmentUtil isAppExtension]) {
  589. [self didCompleteConfigure];
  590. }
  591. }
  592. + (NSError *)configureErrorWithReason:(nonnull NSString *)reason {
  593. NSString *description =
  594. [NSString stringWithFormat:@"Configuration failed for service %@.", kFIRIIDServiceInstanceID];
  595. if (!reason.length) {
  596. reason = @"Unknown reason";
  597. }
  598. NSDictionary *userInfo =
  599. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  600. return [NSError errorWithDomain:kFIRIIDErrorDomain
  601. code:kFIRIIDErrorCodeInstanceIDFailed
  602. userInfo:userInfo];
  603. }
  604. // If the firebaseApp is available we should send logs for the error through it before
  605. // raising an exception.
  606. + (void)exitWithReason:(nonnull NSString *)reason forFirebaseApp:(FIRApp *)firebaseApp {
  607. [firebaseApp sendLogsWithServiceName:kFIRIIDServiceInstanceID
  608. version:FIRInstanceIDCurrentLibraryVersion()
  609. error:[self configureErrorWithReason:reason]];
  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. [self performDefaultTokenHandlerWithToken:token error:nil];
  825. }
  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. Class envClass = NSClassFromString(@"FIRAppEnvironmentUtil");
  924. SEL isSimulatorSelector = NSSelectorFromString(@"isSimulator");
  925. if ([envClass respondsToSelector:isSimulatorSelector]) {
  926. #pragma clang diagnostic push
  927. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  928. if ([envClass performSelector:isSimulatorSelector]) {
  929. #pragma clang diagnostic pop
  930. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  931. @"Use prod profile by default."];
  932. return defaultAppTypeProd;
  933. }
  934. }
  935. NSString *path = [[[NSBundle mainBundle] bundlePath]
  936. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  937. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  938. SEL isFromAppStoreSelector = NSSelectorFromString(@"isFromAppStore");
  939. if ([envClass respondsToSelector:isFromAppStoreSelector]) {
  940. #pragma clang diagnostic push
  941. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  942. if ([envClass performSelector:isFromAppStoreSelector]) {
  943. #pragma clang diagnostic pop
  944. return defaultAppTypeProd;
  945. }
  946. }
  947. SEL isAppStoreReceiptSandboxSelector = NSSelectorFromString(@"isAppStoreReceiptSandbox");
  948. if ([envClass respondsToSelector:isAppStoreReceiptSandboxSelector]) {
  949. #pragma clang diagnostic push
  950. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  951. if ([envClass performSelector:isAppStoreReceiptSandboxSelector] && !path.length) {
  952. #pragma clang diagnostic pop
  953. // Distributed via TestFlight
  954. return defaultAppTypeProd;
  955. }
  956. }
  957. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  958. if (!profileData.length || error) {
  959. NSString *errorString =
  960. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  961. [self logAPNSConfigurationError:errorString];
  962. return defaultAppTypeProd;
  963. }
  964. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  965. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  966. // ASCII. Replace any 0s or invalid characters in the input.
  967. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  968. for (int i = 0; i < profileData.length; i++) {
  969. uint8_t currentByte = profileBytes[i];
  970. if (!currentByte || currentByte > 127) {
  971. profileBytes[i] = '.';
  972. }
  973. }
  974. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  975. length:profileData.length
  976. encoding:NSASCIIStringEncoding
  977. freeWhenDone:NO];
  978. if (error || !embeddedProfile.length) {
  979. NSString *errorString =
  980. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  981. [self logAPNSConfigurationError:errorString];
  982. return defaultAppTypeProd;
  983. }
  984. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  985. NSString *plistContents;
  986. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  987. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  988. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  989. }
  990. }
  991. if (!plistContents.length) {
  992. return defaultAppTypeProd;
  993. }
  994. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  995. if (!data.length) {
  996. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  997. return defaultAppTypeProd;
  998. }
  999. NSError *plistMapError;
  1000. id plistData = [NSPropertyListSerialization propertyListWithData:data
  1001. options:NSPropertyListImmutable
  1002. format:nil
  1003. error:&plistMapError];
  1004. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  1005. NSString *errorString =
  1006. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  1007. plistMapError.localizedDescription];
  1008. [self logAPNSConfigurationError:errorString];
  1009. return defaultAppTypeProd;
  1010. }
  1011. NSDictionary *plistMap = (NSDictionary *)plistData;
  1012. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  1013. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  1014. @"Provisioning profile has specifically provisioned devices, "
  1015. @"most likely a Dev profile.");
  1016. }
  1017. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  1018. NSString *debugString __unused =
  1019. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  1020. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  1021. // No aps-environment in the profile.
  1022. if (!apsEnvironment.length) {
  1023. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  1024. @"correctly configured. Please recheck your provisioning "
  1025. @"profiles. If testing on a simulator this is fine since APNS "
  1026. @"doesn't work on the simulator."];
  1027. return defaultAppTypeProd;
  1028. }
  1029. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  1030. return NO;
  1031. }
  1032. return defaultAppTypeProd;
  1033. }
  1034. /// Log error messages only when Messaging exists in the pod.
  1035. - (void)logAPNSConfigurationError:(NSString *)errorString {
  1036. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  1037. if (hasFirebaseMessaging) {
  1038. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  1039. } else {
  1040. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  1041. }
  1042. }
  1043. @end