FIRInstanceID.m 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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. _FIRInstanceIDDevAssert(handler != nil && [authorizedEntity length] && [scope length],
  223. @"Invalid authorizedEntity or scope to new token");
  224. if (!handler) {
  225. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
  226. kFIRInstanceIDInvalidNilHandlerError);
  227. return;
  228. }
  229. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  230. if (options.count) {
  231. [tokenOptions addEntriesFromDictionary:options];
  232. }
  233. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  234. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  235. if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
  236. // APNS key was given, but server type is missing. Supply the server type with automatic
  237. // checking. This can happen when the token is requested from FCM, which does not include a
  238. // server type during its request.
  239. tokenOptions[serverTypeKey] = @([self isSandboxApp]);
  240. }
  241. // comparing enums to ints directly throws a warning
  242. FIRInstanceIDErrorCode noError = INT_MAX;
  243. FIRInstanceIDErrorCode errorCode = noError;
  244. if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
  245. errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
  246. } else if (FIRInstanceIDIsValidGCMScope(scope) &&
  247. ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
  248. errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
  249. } else if (![authorizedEntity length]) {
  250. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  251. } else if (![scope length]) {
  252. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  253. } else if (!self.keyPairStore) {
  254. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  255. }
  256. FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
  257. dispatch_async(dispatch_get_main_queue(), ^{
  258. handler(token, error);
  259. });
  260. };
  261. if (errorCode != noError) {
  262. newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  263. return;
  264. }
  265. // TODO(chliangGoogle): Add some validation logic that the APNs token data and sandbox value are
  266. // supplied in the valid format (NSData and BOOL, respectively).
  267. // Add internal options
  268. if (self.firebaseAppID) {
  269. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  270. }
  271. FIRInstanceID_WEAKIFY(self);
  272. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  273. [authService
  274. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  275. FIRInstanceID_STRONGIFY(self);
  276. if (error) {
  277. newHandler(nil, error);
  278. return;
  279. }
  280. // Only use the token in the cache if the APNSInfo matches what the request's options has.
  281. // It's possible for the request to be with a newer APNs device token, which should be
  282. // honored.
  283. FIRInstanceIDTokenInfo *cachedTokenInfo =
  284. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  285. if (cachedTokenInfo) {
  286. // Ensure that the cached token matches APNs data before returning it.
  287. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  288. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  289. // If either the APNs info is missing in both, or if they are an exact match, then we can
  290. // use this cached token.
  291. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  292. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  293. newHandler(cachedTokenInfo.token, nil);
  294. return;
  295. }
  296. }
  297. FIRInstanceID_WEAKIFY(self);
  298. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  299. FIRInstanceID_STRONGIFY(self);
  300. if (error) {
  301. NSError *newError =
  302. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  303. newHandler(nil, newError);
  304. } else {
  305. [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  306. scope:[scope copy]
  307. keyPair:keyPair
  308. options:tokenOptions
  309. handler:newHandler];
  310. }
  311. }];
  312. }];
  313. }
  314. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  315. scope:(NSString *)scope
  316. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  317. _FIRInstanceIDDevAssert(handler != nil && [authorizedEntity length] && [scope length],
  318. @"Invalid authorizedEntity or scope to delete token");
  319. if (!handler) {
  320. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
  321. kFIRInstanceIDInvalidNilHandlerError);
  322. }
  323. // comparing enums to ints directly throws a warning
  324. FIRInstanceIDErrorCode noError = INT_MAX;
  325. FIRInstanceIDErrorCode errorCode = noError;
  326. if (![authorizedEntity length]) {
  327. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  328. } else if (![scope length]) {
  329. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  330. } else if (!self.keyPairStore) {
  331. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  332. }
  333. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  334. // If a default token is deleted successfully, reset the defaultFCMToken too.
  335. if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
  336. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
  337. self.defaultFCMToken = nil;
  338. }
  339. dispatch_async(dispatch_get_main_queue(), ^{
  340. handler(error);
  341. });
  342. };
  343. if (errorCode != noError) {
  344. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  345. return;
  346. }
  347. FIRInstanceID_WEAKIFY(self);
  348. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  349. [authService
  350. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  351. FIRInstanceID_STRONGIFY(self);
  352. if (error) {
  353. newHandler(error);
  354. return;
  355. }
  356. FIRInstanceID_WEAKIFY(self);
  357. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  358. FIRInstanceID_STRONGIFY(self);
  359. if (error) {
  360. NSError *newError =
  361. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  362. newHandler(newError);
  363. } else {
  364. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  365. scope:scope
  366. keyPair:keyPair
  367. handler:newHandler];
  368. }
  369. }];
  370. }];
  371. }
  372. - (void)asyncLoadKeyPairWithHandler:(FIRInstanceIDKeyPairHandler)handler {
  373. FIRInstanceID_WEAKIFY(self);
  374. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  375. FIRInstanceID_STRONGIFY(self);
  376. NSError *error = nil;
  377. FIRInstanceIDKeyPair *keyPair = [self.keyPairStore loadKeyPairWithError:&error];
  378. dispatch_async(dispatch_get_main_queue(), ^{
  379. if (error) {
  380. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID002,
  381. @"Failed to retreieve keyPair %@", error);
  382. if (handler) {
  383. handler(nil, error);
  384. }
  385. } else if (!keyPair && !error) {
  386. if (handler) {
  387. handler(nil,
  388. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair]);
  389. }
  390. } else {
  391. if (handler) {
  392. handler(keyPair, nil);
  393. }
  394. }
  395. });
  396. });
  397. }
  398. #pragma mark - Identity
  399. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  400. _FIRInstanceIDDevAssert(handler, @"Invalid nil handler to getIdentity");
  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. _FIRInstanceIDDevAssert(handler, @"Invalid nil handler to delete Identity");
  431. if (!handler) {
  432. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  433. kFIRInstanceIDInvalidNilHandlerError);
  434. return;
  435. }
  436. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  437. if ([NSThread isMainThread]) {
  438. handler(error);
  439. return;
  440. }
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. handler(error);
  443. });
  444. };
  445. if (!self.keyPairStore) {
  446. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  447. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  448. return;
  449. }
  450. FIRInstanceID_WEAKIFY(self);
  451. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  452. FIRInstanceID_STRONGIFY(self);
  453. if (error) {
  454. callHandlerOnMainThread(error);
  455. return;
  456. }
  457. [self deleteIdentityWithHandler:^(NSError *error) {
  458. callHandlerOnMainThread(error);
  459. }];
  460. };
  461. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  462. FIRInstanceID_STRONGIFY(self);
  463. if (error) {
  464. NSError *newError =
  465. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  466. callHandlerOnMainThread(newError);
  467. } else {
  468. [self.tokenManager deleteAllTokensWithKeyPair:keyPair handler:deleteTokensHandler];
  469. }
  470. }];
  471. }
  472. - (void)notifyIdentityReset {
  473. [self deleteIdentityWithHandler:nil];
  474. }
  475. // Delete all the local cache checkin, IID and token.
  476. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  477. // Delete tokens.
  478. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  479. // Reset FCM token.
  480. self.defaultFCMToken = nil;
  481. if (deleteTokenError) {
  482. if (handler) {
  483. handler(deleteTokenError);
  484. }
  485. return;
  486. }
  487. // Delete Instance ID.
  488. [self.keyPairStore
  489. deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  490. handler:^(NSError *error) {
  491. NSError *deletePlistError;
  492. [self.keyPairStore
  493. removeKeyPairCreationTimePlistWithError:&deletePlistError];
  494. if (error || deletePlistError) {
  495. if (handler) {
  496. // Prefer to use the delete Instance ID error.
  497. error = [NSError
  498. errorWithFIRInstanceIDErrorCode:
  499. kFIRInstanceIDErrorCodeUnknown
  500. userInfo:@{
  501. NSUnderlyingErrorKey : error
  502. ? error
  503. : deletePlistError
  504. }];
  505. handler(error);
  506. }
  507. return;
  508. }
  509. // Delete checkin.
  510. [self.tokenManager.authService
  511. resetCheckinWithHandler:^(NSError *error) {
  512. if (error) {
  513. if (handler) {
  514. handler(error);
  515. }
  516. return;
  517. }
  518. // Only request new token if FCM auto initialization is
  519. // enabled.
  520. if ([self isFCMAutoInitEnabled]) {
  521. // Deletion succeeds! Requesting new checkin, IID and token.
  522. // TODO(chliangGoogle) see if dispatch_after is necessary
  523. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  524. (int64_t)(0.5 * NSEC_PER_SEC)),
  525. dispatch_get_main_queue(), ^{
  526. [self defaultTokenWithHandler:nil];
  527. });
  528. }
  529. if (handler) {
  530. handler(nil);
  531. }
  532. }];
  533. }];
  534. }];
  535. }
  536. #pragma mark - Checkin
  537. - (BOOL)tryToLoadValidCheckinInfo {
  538. FIRInstanceIDCheckinPreferences *checkinPreferences =
  539. [self.tokenManager.authService checkinPreferences];
  540. return [checkinPreferences hasValidCheckinInfo];
  541. }
  542. - (NSString *)deviceAuthID {
  543. return [self.tokenManager.authService checkinPreferences].deviceID;
  544. }
  545. - (NSString *)secretToken {
  546. return [self.tokenManager.authService checkinPreferences].secretToken;
  547. }
  548. - (NSString *)versionInfo {
  549. return [self.tokenManager.authService checkinPreferences].versionInfo;
  550. }
  551. #pragma mark - Config
  552. + (void)load {
  553. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  554. withName:@"fire-iid"
  555. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  556. }
  557. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  558. FIRComponentCreationBlock creationBlock =
  559. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  560. // Ensure it's cached so it returns the same instance every time instanceID is called.
  561. *isCacheable = YES;
  562. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  563. [instanceID start];
  564. return instanceID;
  565. };
  566. FIRComponent *instanceIDProvider =
  567. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  568. instantiationTiming:FIRInstantiationTimingLazy
  569. dependencies:@[]
  570. creationBlock:creationBlock];
  571. return @[ instanceIDProvider ];
  572. }
  573. + (void)configureWithApp:(FIRApp *)app {
  574. if (!app.isDefaultApp) {
  575. // Only configure for the default FIRApp.
  576. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  577. @"Firebase Instance ID only works with the default app.");
  578. return;
  579. }
  580. [[FIRInstanceID instanceID] configureInstanceIDWithOptions:app.options app:app];
  581. }
  582. - (void)configureInstanceIDWithOptions:(FIROptions *)options app:(FIRApp *)firApp {
  583. NSString *GCMSenderID = options.GCMSenderID;
  584. if (!GCMSenderID.length) {
  585. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  586. @"Firebase not set up correctly, nil or empty senderID.");
  587. [FIRInstanceID exitWithReason:@"GCM_SENDER_ID must not be nil or empty." forFirebaseApp:firApp];
  588. return;
  589. }
  590. self.fcmSenderID = GCMSenderID;
  591. self.firebaseAppID = firApp.options.googleAppID;
  592. // FCM generates a FCM token during app start for sending push notification to device.
  593. // This is not needed for app extension.
  594. if (![GULAppEnvironmentUtil isAppExtension]) {
  595. [self didCompleteConfigure];
  596. }
  597. }
  598. + (NSError *)configureErrorWithReason:(nonnull NSString *)reason {
  599. NSString *description =
  600. [NSString stringWithFormat:@"Configuration failed for service %@.", kFIRIIDServiceInstanceID];
  601. if (!reason.length) {
  602. reason = @"Unknown reason";
  603. }
  604. NSDictionary *userInfo =
  605. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  606. return [NSError errorWithDomain:kFIRIIDErrorDomain
  607. code:kFIRIIDErrorCodeInstanceIDFailed
  608. userInfo:userInfo];
  609. }
  610. // If the firebaseApp is available we should send logs for the error through it before
  611. // raising an exception.
  612. + (void)exitWithReason:(nonnull NSString *)reason forFirebaseApp:(FIRApp *)firebaseApp {
  613. [firebaseApp sendLogsWithServiceName:kFIRIIDServiceInstanceID
  614. version:FIRInstanceIDCurrentLibraryVersion()
  615. error:[self configureErrorWithReason:reason]];
  616. [NSException raise:kFIRIIDErrorDomain
  617. format:@"Could not configure Firebase InstanceID. %@", reason];
  618. }
  619. // This is used to start any operations when we receive FirebaseSDK setup notification
  620. // from FIRCore.
  621. - (void)didCompleteConfigure {
  622. NSString *cachedToken = [self cachedTokenIfAvailable];
  623. // When there is a cached token, do the token refresh.
  624. if (cachedToken) {
  625. // Clean up expired tokens by checking the token refresh policy.
  626. if ([self.tokenManager checkForTokenRefreshPolicy]) {
  627. // Default token is expired, fetch default token from server.
  628. [self defaultTokenWithHandler:nil];
  629. }
  630. // Notify FCM with the default token.
  631. self.defaultFCMToken = [self token];
  632. } else if ([self isFCMAutoInitEnabled]) {
  633. // When there is no cached token, must check auto init is enabled.
  634. // If it's disabled, don't initiate token generation/refresh.
  635. // If no cache token and auto init is enabled, fetch a token from server.
  636. [self defaultTokenWithHandler:nil];
  637. // Notify FCM with the default token.
  638. self.defaultFCMToken = [self token];
  639. }
  640. // ONLY checkin when auto data collection is turned on.
  641. if ([self isFCMAutoInitEnabled]) {
  642. [self.tokenManager.authService scheduleCheckin:YES];
  643. }
  644. }
  645. - (BOOL)isFCMAutoInitEnabled {
  646. Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
  647. // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
  648. if (!messagingClass) {
  649. return NO;
  650. }
  651. // Messaging doesn't have the singleton method, auto init should be enabled since FCM exists.
  652. SEL instanceSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorInstance);
  653. if (![messagingClass respondsToSelector:instanceSelector]) {
  654. return YES;
  655. }
  656. // Get FIRMessaging shared instance.
  657. IMP messagingInstanceIMP = [messagingClass methodForSelector:instanceSelector];
  658. id (*getMessagingInstance)(id, SEL) = (void *)messagingInstanceIMP;
  659. id messagingInstance = getMessagingInstance(messagingClass, instanceSelector);
  660. // Messaging doesn't have the property, auto init should be enabled since FCM exists.
  661. SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
  662. if (![messagingInstance respondsToSelector:autoInitSelector]) {
  663. return YES;
  664. }
  665. // Get autoInitEnabled method.
  666. IMP isAutoInitEnabledIMP = [messagingInstance methodForSelector:autoInitSelector];
  667. BOOL (*isAutoInitEnabled)(id, SEL) = (BOOL(*)(id, SEL))isAutoInitEnabledIMP;
  668. // Check FCM's isAutoInitEnabled property.
  669. return isAutoInitEnabled(messagingInstance, autoInitSelector);
  670. }
  671. // Actually makes InstanceID instantiate both the IID and Token-related subsystems.
  672. - (void)start {
  673. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  674. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  675. }
  676. [self setupTokenManager];
  677. [self setupKeyPairManager];
  678. [self setupNotificationListeners];
  679. }
  680. // Creates the token manager, which is used for fetching, caching, and retrieving tokens.
  681. - (void)setupTokenManager {
  682. self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
  683. }
  684. // Creates a key pair manager, which stores the public/private keys needed to generate an
  685. // application instance ID.
  686. - (void)setupKeyPairManager {
  687. self.keyPairStore = [[FIRInstanceIDKeyPairStore alloc] init];
  688. if ([self.keyPairStore invalidateKeyPairsIfNeeded]) {
  689. // Reset tokens right away when keypair is deleted, otherwise async call can make first query
  690. // of token happens before reset old tokens during app start.
  691. // TODO(chliangGoogle): Delete all tokens on server too, using
  692. // deleteAllTokensWithKeyPair:handler:. This requires actually retrieving the invalid keypair
  693. // from Keychain, which is something that the key pair store does not currently do.
  694. [self.tokenManager deleteAllTokensLocallyWithHandler:nil];
  695. }
  696. }
  697. - (void)setupNotificationListeners {
  698. // To prevent double notifications remove observer from all events during setup.
  699. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  700. [center removeObserver:self];
  701. [center addObserver:self
  702. selector:@selector(notifyIdentityReset)
  703. name:kFIRInstanceIDIdentityInvalidatedNotification
  704. object:nil];
  705. [center addObserver:self
  706. selector:@selector(notifyAPNSTokenIsSet:)
  707. name:kFIRInstanceIDAPNSTokenNotification
  708. object:nil];
  709. }
  710. #pragma mark - Private Helpers
  711. /// Maximum retry count to fetch the default token.
  712. + (int64_t)maxRetryCountForDefaultToken {
  713. return kMaxRetryCountForDefaultToken;
  714. }
  715. /// Minimum interval in seconds between retries to fetch the default token.
  716. + (int64_t)minIntervalForDefaultTokenRetry {
  717. return kMinRetryIntervalForDefaultTokenInSeconds;
  718. }
  719. /// Maximum retry interval between retries to fetch default token.
  720. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
  721. return kMaxRetryIntervalForDefaultTokenInSeconds;
  722. }
  723. - (NSInteger)retryIntervalToFetchDefaultToken {
  724. if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
  725. return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
  726. }
  727. // exponential backoff with a fixed initial retry time
  728. // 11s, 22s, 44s, 88s ...
  729. int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
  730. return (NSInteger)MIN(
  731. (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
  732. kMaxRetryIntervalForDefaultTokenInSeconds);
  733. }
  734. - (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
  735. [self defaultTokenWithRetry:NO handler:aHandler];
  736. }
  737. /**
  738. * @param retry Indicates if the method is called to perform a retry after a failed attempt.
  739. * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
  740. * nil`
  741. */
  742. - (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
  743. BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
  744. if (!self.defaultTokenFetchHandler) {
  745. self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
  746. }
  747. if (aHandler) {
  748. [self.defaultTokenFetchHandler addHandler:aHandler];
  749. }
  750. if (!shouldPerformRequest) {
  751. return;
  752. }
  753. NSDictionary *instanceIDOptions = @{};
  754. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  755. if (hasFirebaseMessaging && self.apnsTokenData) {
  756. BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
  757. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  758. isSandboxApp = [self isSandboxApp];
  759. }
  760. instanceIDOptions = @{
  761. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  762. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
  763. };
  764. }
  765. FIRInstanceID_WEAKIFY(self);
  766. FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
  767. FIRInstanceID_STRONGIFY(self);
  768. if (error) {
  769. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
  770. @"Failed to fetch default token %@", error);
  771. // This notification can be sent multiple times since we can't guarantee success at any point
  772. // of time.
  773. NSNotification *tokenFetchFailNotification =
  774. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
  775. object:[error copy]];
  776. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
  777. postingStyle:NSPostASAP];
  778. self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
  779. [[self class] maxRetryCountForDefaultToken]);
  780. // Do not retry beyond the maximum limit.
  781. if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
  782. NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
  783. [self retryGetDefaultTokenAfter:retryInterval];
  784. } else {
  785. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
  786. @"Failed to retrieve the default FCM token after %ld retries",
  787. (long)self.retryCountForDefaultToken);
  788. [self performDefaultTokenHandlerWithToken:nil error:error];
  789. }
  790. } else {
  791. // If somebody updated IID with APNS token while our initial request did not have it
  792. // set we need to update it on the server.
  793. NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
  794. BOOL isSandboxInRequest =
  795. [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
  796. // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
  797. NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  798. deviceTokenInRequest, isSandboxInRequest);
  799. // If the APNs value either remained nil, or was the same non-nil value, the APNs value
  800. // did not change.
  801. BOOL APNSRemainedSameDuringFetch =
  802. (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
  803. ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
  804. if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
  805. // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
  806. // value.
  807. [self retryGetDefaultTokenAfter:0];
  808. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
  809. @"Received APNS token while fetching default token. "
  810. @"Refetching default token.");
  811. // Do not notify and handle completion handler since this is a retry.
  812. // Simply return.
  813. return;
  814. } else {
  815. FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
  816. @"Successfully fetched default token.");
  817. }
  818. // Post the required notifications if somebody is waiting.
  819. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
  820. token);
  821. NSString *previousFCMToken = self.defaultFCMToken;
  822. self.defaultFCMToken = token;
  823. // Only notify of token refresh if we have a new valid token that's different than before
  824. if (self.defaultFCMToken.length && ![self.defaultFCMToken isEqualToString:previousFCMToken]) {
  825. NSNotification *tokenRefreshNotification =
  826. [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
  827. object:[self.defaultFCMToken copy]];
  828. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
  829. postingStyle:NSPostASAP];
  830. [self performDefaultTokenHandlerWithToken:token error:nil];
  831. }
  832. }
  833. };
  834. [self tokenWithAuthorizedEntity:self.fcmSenderID
  835. scope:kFIRInstanceIDDefaultTokenScope
  836. options:instanceIDOptions
  837. handler:newHandler];
  838. }
  839. /**
  840. *
  841. */
  842. - (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
  843. if (!self.defaultTokenFetchHandler) {
  844. return;
  845. }
  846. [self.defaultTokenFetchHandler combinedHandler](token, error);
  847. self.defaultTokenFetchHandler = nil;
  848. }
  849. - (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
  850. FIRInstanceID_WEAKIFY(self);
  851. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
  852. dispatch_get_main_queue(), ^{
  853. FIRInstanceID_STRONGIFY(self);
  854. // Pass nil: no new handlers to be added, currently existing handlers
  855. // will be called
  856. [self defaultTokenWithRetry:YES handler:nil];
  857. });
  858. }
  859. #pragma mark - APNS Token
  860. // This should only be triggered from FCM.
  861. - (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
  862. NSData *token = notification.object;
  863. if (!token || ![token isKindOfClass:[NSData class]]) {
  864. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
  865. NSStringFromClass([notification.object class]));
  866. return;
  867. }
  868. NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
  869. // The APNS token is being added, or has changed (rare)
  870. if ([self.apnsTokenData isEqualToData:token]) {
  871. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
  872. @"Trying to reset APNS token to the same value. Will return");
  873. return;
  874. }
  875. // Use this token type for when we have to automatically fetch tokens in the future
  876. self.apnsTokenType = type;
  877. BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
  878. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  879. isSandboxApp = [self isSandboxApp];
  880. }
  881. self.apnsTokenData = [token copy];
  882. self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
  883. // Pro-actively invalidate the default token, if the APNs change makes it
  884. // invalid. Previously, we invalidated just before fetching the token.
  885. NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
  886. [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
  887. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  888. // they are up-to-date.
  889. if (invalidatedTokens.count > 0) {
  890. FIRInstanceID_WEAKIFY(self);
  891. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  892. FIRInstanceID_STRONGIFY(self);
  893. NSMutableDictionary *tokenOptions = [@{
  894. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  895. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  896. } mutableCopy];
  897. if (self.firebaseAppID) {
  898. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  899. }
  900. for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
  901. if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
  902. // We will perform a special fetch for the default FCM token, so that the delegate methods
  903. // are called. For all others, we will do an internal re-fetch.
  904. [self defaultTokenWithHandler:nil];
  905. } else {
  906. [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  907. scope:tokenInfo.scope
  908. keyPair:keyPair
  909. options:tokenOptions
  910. handler:^(NSString *_Nullable token,
  911. NSError *_Nullable error){
  912. }];
  913. }
  914. }
  915. }];
  916. }
  917. }
  918. - (BOOL)isSandboxApp {
  919. static BOOL isSandboxApp = YES;
  920. static dispatch_once_t onceToken;
  921. dispatch_once(&onceToken, ^{
  922. isSandboxApp = ![self isProductionApp];
  923. });
  924. return isSandboxApp;
  925. }
  926. - (BOOL)isProductionApp {
  927. const BOOL defaultAppTypeProd = YES;
  928. NSError *error = nil;
  929. Class envClass = NSClassFromString(@"FIRAppEnvironmentUtil");
  930. SEL isSimulatorSelector = NSSelectorFromString(@"isSimulator");
  931. if ([envClass respondsToSelector:isSimulatorSelector]) {
  932. #pragma clang diagnostic push
  933. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  934. if ([envClass performSelector:isSimulatorSelector]) {
  935. #pragma clang diagnostic pop
  936. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  937. @"Use prod profile by default."];
  938. return defaultAppTypeProd;
  939. }
  940. }
  941. NSString *path = [[[NSBundle mainBundle] bundlePath]
  942. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  943. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  944. SEL isFromAppStoreSelector = NSSelectorFromString(@"isFromAppStore");
  945. if ([envClass respondsToSelector:isFromAppStoreSelector]) {
  946. #pragma clang diagnostic push
  947. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  948. if ([envClass performSelector:isFromAppStoreSelector]) {
  949. #pragma clang diagnostic pop
  950. return defaultAppTypeProd;
  951. }
  952. }
  953. SEL isAppStoreReceiptSandboxSelector = NSSelectorFromString(@"isAppStoreReceiptSandbox");
  954. if ([envClass respondsToSelector:isAppStoreReceiptSandboxSelector]) {
  955. #pragma clang diagnostic push
  956. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  957. if ([envClass performSelector:isAppStoreReceiptSandboxSelector] && !path.length) {
  958. #pragma clang diagnostic pop
  959. // Distributed via TestFlight
  960. return defaultAppTypeProd;
  961. }
  962. }
  963. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  964. if (!profileData.length || error) {
  965. NSString *errorString =
  966. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  967. [self logAPNSConfigurationError:errorString];
  968. return defaultAppTypeProd;
  969. }
  970. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  971. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  972. // ASCII. Replace any 0s or invalid characters in the input.
  973. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  974. for (int i = 0; i < profileData.length; i++) {
  975. uint8_t currentByte = profileBytes[i];
  976. if (!currentByte || currentByte > 127) {
  977. profileBytes[i] = '.';
  978. }
  979. }
  980. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  981. length:profileData.length
  982. encoding:NSASCIIStringEncoding
  983. freeWhenDone:NO];
  984. if (error || !embeddedProfile.length) {
  985. NSString *errorString =
  986. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  987. [self logAPNSConfigurationError:errorString];
  988. return defaultAppTypeProd;
  989. }
  990. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  991. NSString *plistContents;
  992. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  993. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  994. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  995. }
  996. }
  997. if (!plistContents.length) {
  998. return defaultAppTypeProd;
  999. }
  1000. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  1001. if (!data.length) {
  1002. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  1003. return defaultAppTypeProd;
  1004. }
  1005. NSError *plistMapError;
  1006. id plistData = [NSPropertyListSerialization propertyListWithData:data
  1007. options:NSPropertyListImmutable
  1008. format:nil
  1009. error:&plistMapError];
  1010. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  1011. NSString *errorString =
  1012. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  1013. plistMapError.localizedDescription];
  1014. [self logAPNSConfigurationError:errorString];
  1015. return defaultAppTypeProd;
  1016. }
  1017. NSDictionary *plistMap = (NSDictionary *)plistData;
  1018. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  1019. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  1020. @"Provisioning profile has specifically provisioned devices, "
  1021. @"most likely a Dev profile.");
  1022. }
  1023. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  1024. NSString *debugString __unused =
  1025. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  1026. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  1027. // No aps-environment in the profile.
  1028. if (!apsEnvironment.length) {
  1029. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  1030. @"correctly configured. Please recheck your provisioning "
  1031. @"profiles. If testing on a simulator this is fine since APNS "
  1032. @"doesn't work on the simulator."];
  1033. return defaultAppTypeProd;
  1034. }
  1035. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  1036. return NO;
  1037. }
  1038. return defaultAppTypeProd;
  1039. }
  1040. /// Log error messages only when Messaging exists in the pod.
  1041. - (void)logAPNSConfigurationError:(NSString *)errorString {
  1042. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  1043. if (hasFirebaseMessaging) {
  1044. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  1045. } else {
  1046. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  1047. }
  1048. }
  1049. @end