No Description

FIRInstanceID.m 45KB

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