FIRInstanceID.m 48 KB

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