Nessuna descrizione

FIRInstanceID.m 46KB

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