FIRInstanceID.m 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 "FIRInstanceIDCombinedHandler.h"
  26. #import "FIRInstanceIDConstants.h"
  27. #import "FIRInstanceIDDefines.h"
  28. #import "FIRInstanceIDKeyPairStore.h"
  29. #import "FIRInstanceIDLogger.h"
  30. #import "FIRInstanceIDStore.h"
  31. #import "FIRInstanceIDTokenInfo.h"
  32. #import "FIRInstanceIDTokenManager.h"
  33. #import "FIRInstanceIDUtilities.h"
  34. #import "FIRInstanceIDVersionUtilities.h"
  35. #import "NSError+FIRInstanceID.h"
  36. // Public constants
  37. NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
  38. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  39. const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
  40. @"com.firebase.iid.notif.refresh-token";
  41. #else
  42. NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
  43. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  44. NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
  45. // Private constants
  46. int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60; // 20 minutes
  47. int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10; // 10 seconds
  48. // we retry only a max 5 times.
  49. // TODO(chliangGoogle): If we still fail we should listen for the network change notification
  50. // since GCM would have started Reachability. We only start retrying after we see a configuration
  51. // change.
  52. NSInteger const kMaxRetryCountForDefaultToken = 5;
  53. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  54. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  55. /// FIRMessaging selector that returns the current FIRMessaging auto init
  56. /// enabled flag.
  57. static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled = @"isAutoInitEnabled";
  58. static NSString *const kFIRInstanceIDFCMSelectorInstance = @"messaging";
  59. static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
  60. static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
  61. @"FIRAppReadyToConfigureSDKNotification";
  62. static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
  63. static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
  64. static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
  65. // This should be the same value as FIRErrorCodeInstanceIDFailed, which we can't import directly
  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. #pragma clang diagnostic push
  425. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  426. [self token];
  427. #pragma clang diagnostic pop
  428. }
  429. callHandlerOnMainThread(appIdentity, error);
  430. });
  431. }
  432. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  433. _FIRInstanceIDDevAssert(handler, @"Invalid nil handler to delete Identity");
  434. if (!handler) {
  435. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  436. kFIRInstanceIDInvalidNilHandlerError);
  437. return;
  438. }
  439. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  440. if ([NSThread isMainThread]) {
  441. handler(error);
  442. return;
  443. }
  444. dispatch_async(dispatch_get_main_queue(), ^{
  445. handler(error);
  446. });
  447. };
  448. if (!self.keyPairStore) {
  449. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  450. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  451. return;
  452. }
  453. FIRInstanceID_WEAKIFY(self);
  454. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  455. FIRInstanceID_STRONGIFY(self);
  456. if (error) {
  457. callHandlerOnMainThread(error);
  458. return;
  459. }
  460. [self deleteIdentityWithHandler:^(NSError *error) {
  461. callHandlerOnMainThread(error);
  462. }];
  463. };
  464. [self asyncLoadKeyPairWithHandler:^(FIRInstanceIDKeyPair *keyPair, NSError *error) {
  465. FIRInstanceID_STRONGIFY(self);
  466. if (error) {
  467. NSError *newError =
  468. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  469. callHandlerOnMainThread(newError);
  470. } else {
  471. [self.tokenManager deleteAllTokensWithKeyPair:keyPair handler:deleteTokensHandler];
  472. }
  473. }];
  474. }
  475. - (void)notifyIdentityReset {
  476. [self deleteIdentityWithHandler:nil];
  477. }
  478. // Delete all the local cache checkin, IID and token.
  479. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  480. // Delete tokens.
  481. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  482. // Reset FCM token.
  483. self.defaultFCMToken = nil;
  484. if (deleteTokenError) {
  485. if (handler) {
  486. handler(deleteTokenError);
  487. }
  488. return;
  489. }
  490. // Delete Instance ID.
  491. [self.keyPairStore
  492. deleteSavedKeyPairWithSubtype:kFIRInstanceIDKeyPairSubType
  493. handler:^(NSError *error) {
  494. NSError *deletePlistError;
  495. [self.keyPairStore
  496. removeKeyPairCreationTimePlistWithError:&deletePlistError];
  497. if (error || deletePlistError) {
  498. if (handler) {
  499. // Prefer to use the delete Instance ID error.
  500. error = [NSError
  501. errorWithFIRInstanceIDErrorCode:
  502. kFIRInstanceIDErrorCodeUnknown
  503. userInfo:@{
  504. NSUnderlyingErrorKey : error
  505. ? error
  506. : deletePlistError
  507. }];
  508. handler(error);
  509. }
  510. return;
  511. }
  512. // Delete checkin.
  513. [self.tokenManager.authService
  514. resetCheckinWithHandler:^(NSError *error) {
  515. if (error) {
  516. if (handler) {
  517. handler(error);
  518. }
  519. return;
  520. }
  521. // Only request new token if FCM auto initialization is
  522. // enabled.
  523. if ([self isFCMAutoInitEnabled]) {
  524. // Deletion succeeds! Requesting new checkin, IID and token.
  525. // TODO(chliangGoogle) see if dispatch_after is necessary
  526. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  527. (int64_t)(0.5 * NSEC_PER_SEC)),
  528. dispatch_get_main_queue(), ^{
  529. [self defaultTokenWithHandler:nil];
  530. });
  531. }
  532. if (handler) {
  533. handler(nil);
  534. }
  535. }];
  536. }];
  537. }];
  538. }
  539. #pragma mark - Config
  540. + (void)load {
  541. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  542. withName:@"fire-iid"
  543. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  544. }
  545. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  546. FIRComponentCreationBlock creationBlock =
  547. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  548. // Ensure it's cached so it returns the same instance every time instanceID is called.
  549. *isCacheable = YES;
  550. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  551. [instanceID start];
  552. return instanceID;
  553. };
  554. FIRComponent *instanceIDProvider =
  555. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  556. instantiationTiming:FIRInstantiationTimingLazy
  557. dependencies:@[]
  558. creationBlock:creationBlock];
  559. return @[ instanceIDProvider ];
  560. }
  561. + (void)configureWithApp:(FIRApp *)app {
  562. if (!app.isDefaultApp) {
  563. // Only configure for the default FIRApp.
  564. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  565. @"Firebase Instance ID only works with the default app.");
  566. return;
  567. }
  568. [[FIRInstanceID instanceID] configureInstanceIDWithOptions:app.options app:app];
  569. }
  570. - (void)configureInstanceIDWithOptions:(FIROptions *)options app:(FIRApp *)firApp {
  571. NSString *GCMSenderID = options.GCMSenderID;
  572. if (!GCMSenderID.length) {
  573. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  574. @"Firebase not set up correctly, nil or empty senderID.");
  575. [FIRInstanceID exitWithReason:@"GCM_SENDER_ID must not be nil or empty." forFirebaseApp:firApp];
  576. return;
  577. }
  578. self.fcmSenderID = GCMSenderID;
  579. self.firebaseAppID = firApp.options.googleAppID;
  580. // FCM generates a FCM token during app start for sending push notification to device.
  581. // This is not needed for app extension.
  582. if (![GULAppEnvironmentUtil isAppExtension]) {
  583. [self didCompleteConfigure];
  584. }
  585. }
  586. + (NSError *)configureErrorWithReason:(nonnull NSString *)reason {
  587. NSString *description =
  588. [NSString stringWithFormat:@"Configuration failed for service %@.", kFIRIIDServiceInstanceID];
  589. if (!reason.length) {
  590. reason = @"Unknown reason";
  591. }
  592. NSDictionary *userInfo =
  593. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  594. return [NSError errorWithDomain:kFIRIIDErrorDomain
  595. code:kFIRIIDErrorCodeInstanceIDFailed
  596. userInfo:userInfo];
  597. }
  598. // If the firebaseApp is available we should send logs for the error through it before
  599. // raising an exception.
  600. + (void)exitWithReason:(nonnull NSString *)reason forFirebaseApp:(FIRApp *)firebaseApp {
  601. [firebaseApp sendLogsWithServiceName:kFIRIIDServiceInstanceID
  602. version:FIRInstanceIDCurrentLibraryVersion()
  603. error:[self configureErrorWithReason:reason]];
  604. [NSException raise:kFIRIIDErrorDomain
  605. format:@"Could not configure Firebase InstanceID. %@", reason];
  606. }
  607. // This is used to start any operations when we receive FirebaseSDK setup notification
  608. // from FIRCore.
  609. - (void)didCompleteConfigure {
  610. NSString *cachedToken = [self cachedTokenIfAvailable];
  611. // When there is a cached token, do the token refresh.
  612. if (cachedToken) {
  613. // Clean up expired tokens by checking the token refresh policy.
  614. if ([self.tokenManager checkForTokenRefreshPolicy]) {
  615. // Default token is expired, fetch default token from server.
  616. [self defaultTokenWithHandler:nil];
  617. }
  618. // Notify FCM with the default token.
  619. #pragma clang diagnostic push
  620. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  621. self.defaultFCMToken = [self token];
  622. #pragma clang diagnostic pop
  623. } else if ([self isFCMAutoInitEnabled]) {
  624. // When there is no cached token, must check auto init is enabled.
  625. // If it's disabled, don't initiate token generation/refresh.
  626. // If no cache token and auto init is enabled, fetch a token from server.
  627. [self defaultTokenWithHandler:nil];
  628. // Notify FCM with the default token.
  629. #pragma clang diagnostic push
  630. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  631. self.defaultFCMToken = [self token];
  632. #pragma clang diagnostic pop
  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