FIRApp.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <sys/utsname.h>
  15. #if __has_include(<UIKit/UIKit.h>)
  16. #import <UIKit/UIKit.h>
  17. #endif
  18. #if __has_include(<AppKit/AppKit.h>)
  19. #import <AppKit/AppKit.h>
  20. #endif
  21. #if __has_include(<WatchKit/WatchKit.h>)
  22. #import <WatchKit/WatchKit.h>
  23. #endif
  24. #import "FirebaseCore/Sources/Public/FirebaseCore/FIRApp.h"
  25. #import "FirebaseCore/Sources/FIRAnalyticsConfiguration.h"
  26. #import "FirebaseCore/Sources/FIRBundleUtil.h"
  27. #import "FirebaseCore/Sources/FIRComponentContainerInternal.h"
  28. #import "FirebaseCore/Sources/FIRConfigurationInternal.h"
  29. #import "FirebaseCore/Sources/FIRFirebaseUserAgent.h"
  30. #import "FirebaseCore/Extension/FIRAppInternal.h"
  31. #import "FirebaseCore/Extension/FIRHeartbeatLogger.h"
  32. #import "FirebaseCore/Extension/FIRLibrary.h"
  33. #import "FirebaseCore/Extension/FIRLogger.h"
  34. #import "FirebaseCore/Sources/FIROptionsInternal.h"
  35. #import "FirebaseCore/Sources/Public/FirebaseCore/FIROptions.h"
  36. #import "FirebaseCore/Sources/Public/FirebaseCore/FIRVersion.h"
  37. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  38. #import <objc/runtime.h>
  39. NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT";
  40. NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification";
  41. NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification";
  42. NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey";
  43. NSString *const kFIRAppNameKey = @"FIRAppNameKey";
  44. NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey";
  45. NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat =
  46. @"/google/firebase/global_data_collection_enabled:%@";
  47. NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey =
  48. @"FirebaseDataCollectionDefaultEnabled";
  49. NSString *const kFIRAppDiagnosticsConfigurationTypeKey = @"ConfigType";
  50. NSString *const kFIRAppDiagnosticsErrorKey = @"Error";
  51. NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRApp";
  52. NSString *const kFIRAppDiagnosticsSDKNameKey = @"SDKName";
  53. NSString *const kFIRAppDiagnosticsSDKVersionKey = @"SDKVersion";
  54. NSString *const kFIRAppDiagnosticsApplePlatformPrefix = @"apple-platform";
  55. // Auth internal notification notification and key.
  56. NSString *const FIRAuthStateDidChangeInternalNotification =
  57. @"FIRAuthStateDidChangeInternalNotification";
  58. NSString *const FIRAuthStateDidChangeInternalNotificationAppKey =
  59. @"FIRAuthStateDidChangeInternalNotificationAppKey";
  60. NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey =
  61. @"FIRAuthStateDidChangeInternalNotificationTokenKey";
  62. NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey =
  63. @"FIRAuthStateDidChangeInternalNotificationUIDKey";
  64. /**
  65. * Error domain for exceptions and NSError construction.
  66. */
  67. NSString *const kFirebaseCoreErrorDomain = @"com.firebase.core";
  68. /**
  69. * The URL to download plist files.
  70. */
  71. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  72. @interface FIRApp ()
  73. #ifdef DEBUG
  74. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  75. #endif // DEBUG
  76. @end
  77. @implementation FIRApp
  78. // This is necessary since our custom getter prevents `_options` from being created.
  79. @synthesize options = _options;
  80. static NSMutableDictionary *sAllApps;
  81. static FIRApp *sDefaultApp;
  82. + (void)configure {
  83. FIROptions *options = [FIROptions defaultOptions];
  84. if (!options) {
  85. #if DEBUG
  86. [self findMisnamedGoogleServiceInfoPlist];
  87. #endif // DEBUG
  88. [NSException raise:kFirebaseCoreErrorDomain
  89. format:@"`FirebaseApp.configure()` could not find "
  90. @"a valid GoogleService-Info.plist in your project. Please download one "
  91. @"from %@.",
  92. kPlistURL];
  93. }
  94. [FIRApp configureWithOptions:options];
  95. }
  96. + (void)configureWithOptions:(FIROptions *)options {
  97. if (!options) {
  98. [NSException raise:kFirebaseCoreErrorDomain
  99. format:@"Options is nil. Please pass a valid options."];
  100. }
  101. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  102. }
  103. + (NSCharacterSet *)applicationNameAllowedCharacters {
  104. static NSCharacterSet *applicationNameAllowedCharacters;
  105. static dispatch_once_t onceToken;
  106. dispatch_once(&onceToken, ^{
  107. NSMutableCharacterSet *allowedNameCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  108. [allowedNameCharacters addCharactersInString:@"-_"];
  109. applicationNameAllowedCharacters = [allowedNameCharacters copy];
  110. });
  111. return applicationNameAllowedCharacters;
  112. }
  113. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  114. if (!name || !options) {
  115. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  116. }
  117. if (name.length == 0) {
  118. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  119. }
  120. if ([name isEqualToString:kFIRDefaultAppName]) {
  121. if (sDefaultApp) {
  122. // The default app already exists. Handle duplicate `configure` calls and return.
  123. [self appWasConfiguredTwice:sDefaultApp usingOptions:options];
  124. return;
  125. }
  126. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  127. } else {
  128. // Validate the app name and ensure it hasn't been configured already.
  129. NSCharacterSet *nameCharacters = [NSCharacterSet characterSetWithCharactersInString:name];
  130. if (![[self applicationNameAllowedCharacters] isSupersetOfSet:nameCharacters]) {
  131. [NSException raise:kFirebaseCoreErrorDomain
  132. format:@"App name can only contain alphanumeric, "
  133. @"hyphen (-), and underscore (_) characters"];
  134. }
  135. @synchronized(self) {
  136. if (sAllApps && sAllApps[name]) {
  137. // The app already exists. Handle a duplicate `configure` call and return.
  138. [self appWasConfiguredTwice:sAllApps[name] usingOptions:options];
  139. return;
  140. }
  141. }
  142. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  143. }
  144. // Default instantiation, make sure we populate with Swift SDKs that can't register in time.
  145. static dispatch_once_t onceToken;
  146. dispatch_once(&onceToken, ^{
  147. [self registerSwiftComponents];
  148. });
  149. @synchronized(self) {
  150. FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options];
  151. if (app.isDefaultApp) {
  152. sDefaultApp = app;
  153. }
  154. [FIRApp addAppToAppDictionary:app];
  155. // The FIRApp instance is ready to go, `sDefaultApp` is assigned, other SDKs are now ready to be
  156. // instantiated.
  157. [app.container instantiateEagerComponents];
  158. [FIRApp sendNotificationsToSDKs:app];
  159. }
  160. }
  161. /// Called when `configure` has been called multiple times for the same app. This can either throw
  162. /// an exception (most cases) or ignore the duplicate configuration in situations where it's allowed
  163. /// like an extension.
  164. + (void)appWasConfiguredTwice:(FIRApp *)app usingOptions:(FIROptions *)options {
  165. // Only extensions should potentially be able to call `configure` more than once.
  166. if (![GULAppEnvironmentUtil isAppExtension]) {
  167. // Throw an exception since this is now an invalid state.
  168. if (app.isDefaultApp) {
  169. [NSException raise:kFirebaseCoreErrorDomain
  170. format:@"Default app has already been configured."];
  171. } else {
  172. [NSException raise:kFirebaseCoreErrorDomain
  173. format:@"App named %@ has already been configured.", app.name];
  174. }
  175. }
  176. // In an extension, the entry point could be called multiple times. As long as the options are
  177. // identical we should allow multiple `configure` calls.
  178. if ([options isEqual:app.options]) {
  179. // Everything is identical but the extension's lifecycle triggered `configure` twice.
  180. // Ignore duplicate calls and return since everything should still be in a valid state.
  181. FIRLogDebug(kFIRLoggerCore, @"I-COR000035",
  182. @"Ignoring second `configure` call in an extension.");
  183. return;
  184. } else {
  185. [NSException raise:kFirebaseCoreErrorDomain
  186. format:@"App named %@ has already been configured.", app.name];
  187. }
  188. }
  189. + (FIRApp *)defaultApp {
  190. if (sDefaultApp) {
  191. return sDefaultApp;
  192. }
  193. FIRLogError(kFIRLoggerCore, @"I-COR000003",
  194. @"The default Firebase app has not yet been "
  195. @"configured. Add `FirebaseApp.configure()` to your "
  196. @"application initialization. This can be done in "
  197. @"in the App Delegate's application(_:didFinishLaunchingWithOptions:)` "
  198. @"(or the `@main` struct's initializer in SwiftUI). "
  199. @"Read more: "
  200. @"https://firebase.google.com/docs/ios/setup#initialize_firebase_in_your_app");
  201. return nil;
  202. }
  203. + (FIRApp *)appNamed:(NSString *)name {
  204. @synchronized(self) {
  205. if (sAllApps) {
  206. FIRApp *app = sAllApps[name];
  207. if (app) {
  208. return app;
  209. }
  210. }
  211. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  212. return nil;
  213. }
  214. }
  215. + (NSDictionary *)allApps {
  216. @synchronized(self) {
  217. if (!sAllApps) {
  218. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  219. }
  220. return [sAllApps copy];
  221. }
  222. }
  223. // Public only for tests
  224. + (void)resetApps {
  225. @synchronized(self) {
  226. sDefaultApp = nil;
  227. [sAllApps removeAllObjects];
  228. sAllApps = nil;
  229. [[self userAgent] reset];
  230. }
  231. }
  232. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  233. @synchronized([self class]) {
  234. if (sAllApps && sAllApps[self.name]) {
  235. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  236. // Remove all registered libraries from the container to avoid creating new instances.
  237. [self.container removeAllComponents];
  238. // Remove all cached instances from the container before deleting the app.
  239. [self.container removeAllCachedInstances];
  240. [sAllApps removeObjectForKey:self.name];
  241. [self clearDataCollectionSwitchFromUserDefaults];
  242. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  243. sDefaultApp = nil;
  244. }
  245. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  246. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  247. object:[self class]
  248. userInfo:appInfoDict];
  249. completion(YES);
  250. } else {
  251. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  252. completion(NO);
  253. }
  254. }
  255. }
  256. + (void)addAppToAppDictionary:(FIRApp *)app {
  257. if (!sAllApps) {
  258. sAllApps = [NSMutableDictionary dictionary];
  259. }
  260. if ([app configureCore]) {
  261. sAllApps[app.name] = app;
  262. } else {
  263. [NSException raise:kFirebaseCoreErrorDomain
  264. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  265. @"GoogleService-Info.plist or set in the customized options."];
  266. }
  267. }
  268. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  269. self = [super init];
  270. if (self) {
  271. _name = [name copy];
  272. _options = [options copy];
  273. _options.editingLocked = YES;
  274. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  275. _container = [[FIRComponentContainer alloc] initWithApp:self];
  276. _heartbeatLogger = [[FIRHeartbeatLogger alloc] initWithAppID:self.options.googleAppID];
  277. }
  278. return self;
  279. }
  280. - (void)dealloc {
  281. [[NSNotificationCenter defaultCenter] removeObserver:self];
  282. }
  283. - (BOOL)configureCore {
  284. [self checkExpectedBundleID];
  285. if (![self isAppIDValid]) {
  286. return NO;
  287. }
  288. // Initialize the Analytics once there is a valid options under default app. Analytics should
  289. // always initialize first by itself before the other SDKs.
  290. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  291. Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics");
  292. if (firAnalyticsClass) {
  293. #pragma clang diagnostic push
  294. #pragma clang diagnostic ignored "-Wundeclared-selector"
  295. SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:);
  296. #pragma clang diagnostic pop
  297. if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) {
  298. #pragma clang diagnostic push
  299. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  300. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  301. [firAnalyticsClass performSelector:startWithConfigurationSelector
  302. withObject:[FIRConfiguration sharedInstance].analyticsConfiguration
  303. withObject:_options];
  304. #pragma clang diagnostic pop
  305. }
  306. }
  307. }
  308. [self subscribeForAppDidBecomeActiveNotifications];
  309. return YES;
  310. }
  311. - (FIROptions *)options {
  312. return [_options copy];
  313. }
  314. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  315. #ifdef DEBUG
  316. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  317. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  318. self.alreadyOutputDataCollectionFlag = YES;
  319. #endif // DEBUG
  320. NSString *key =
  321. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  322. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  323. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  324. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  325. // default app, so return if this isn't the default app.
  326. if (!self.isDefaultApp) {
  327. return;
  328. }
  329. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  330. if ([self.options isAnalyticsCollectionExplicitlySet]) {
  331. return;
  332. }
  333. // The Analytics flag has not been explicitly set, so update with the value being set.
  334. #pragma clang diagnostic push
  335. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  336. [[FIRAnalyticsConfiguration sharedInstance]
  337. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  338. persistSetting:NO];
  339. #pragma clang diagnostic pop
  340. }
  341. - (BOOL)isDataCollectionDefaultEnabled {
  342. // Check if it's been manually set before in code, and use that as the higher priority value.
  343. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  344. if (defaultsObject != nil) {
  345. #ifdef DEBUG
  346. if (!self.alreadyOutputDataCollectionFlag) {
  347. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  348. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  349. self.alreadyOutputDataCollectionFlag = YES;
  350. }
  351. #endif // DEBUG
  352. return [defaultsObject boolValue];
  353. }
  354. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  355. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  356. // no performance impact calling multiple times.
  357. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  358. if (collectionEnabledPlistValue != nil) {
  359. #ifdef DEBUG
  360. if (!self.alreadyOutputDataCollectionFlag) {
  361. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  362. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  363. self.alreadyOutputDataCollectionFlag = YES;
  364. }
  365. #endif // DEBUG
  366. return [collectionEnabledPlistValue boolValue];
  367. }
  368. #ifdef DEBUG
  369. if (!self.alreadyOutputDataCollectionFlag) {
  370. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  371. self.alreadyOutputDataCollectionFlag = YES;
  372. }
  373. #endif // DEBUG
  374. return YES;
  375. }
  376. #pragma mark - private
  377. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  378. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  379. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  380. NSDictionary *appInfoDict = @{
  381. kFIRAppNameKey : app.name,
  382. kFIRAppIsDefaultAppKey : isDefaultApp,
  383. kFIRGoogleAppIDKey : app.options.googleAppID
  384. };
  385. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  386. object:self
  387. userInfo:appInfoDict];
  388. }
  389. + (BOOL)isDefaultAppConfigured {
  390. return (sDefaultApp != nil);
  391. }
  392. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  393. // Create the set of characters which aren't allowed, only if this feature is used.
  394. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  395. [allowedSet addCharactersInString:@"-_."];
  396. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  397. // Make sure the library name and version strings do not contain unexpected characters, and
  398. // add the name/version pair to the dictionary.
  399. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  400. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  401. [[self userAgent] setValue:version forComponent:name];
  402. } else {
  403. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  404. @"The library name (%@) or version number (%@) contain invalid characters. "
  405. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  406. name, version);
  407. }
  408. }
  409. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  410. withName:(nonnull NSString *)name {
  411. [self registerInternalLibrary:library withName:name withVersion:FIRFirebaseVersion()];
  412. }
  413. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  414. withName:(nonnull NSString *)name
  415. withVersion:(nonnull NSString *)version {
  416. // This is called at +load time, keep the work to a minimum.
  417. // Ensure the class given conforms to the proper protocol.
  418. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  419. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  420. [NSException raise:NSInvalidArgumentException
  421. format:@"Class %@ attempted to register components, but it does not conform to "
  422. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  423. library];
  424. }
  425. [FIRComponentContainer registerAsComponentRegistrant:library];
  426. [self registerLibrary:name withVersion:version];
  427. }
  428. + (FIRFirebaseUserAgent *)userAgent {
  429. static dispatch_once_t onceToken;
  430. static FIRFirebaseUserAgent *_userAgent;
  431. dispatch_once(&onceToken, ^{
  432. _userAgent = [[FIRFirebaseUserAgent alloc] init];
  433. [_userAgent setValue:FIRFirebaseVersion() forComponent:@"fire-ios"];
  434. });
  435. return _userAgent;
  436. }
  437. + (NSString *)firebaseUserAgent {
  438. return [[self userAgent] firebaseUserAgent];
  439. }
  440. - (void)checkExpectedBundleID {
  441. NSArray *bundles = [FIRBundleUtil relevantBundles];
  442. NSString *expectedBundleID = [self expectedBundleID];
  443. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  444. // backward compatibility.
  445. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  446. inBundles:bundles]) {
  447. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  448. @"The project's Bundle ID is inconsistent with "
  449. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  450. @"using a customized options. To ensure that everything can be configured "
  451. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  452. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  453. @"download a new configuration file that matches your bundle identifier from %@ "
  454. @"and replace the current one.",
  455. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  456. }
  457. }
  458. #pragma mark - private - App ID Validation
  459. /**
  460. * Validates the format of app ID and its included bundle ID hash contained in GOOGLE_APP_ID in the
  461. * plist file. This is the main method for validating app ID.
  462. *
  463. * @return YES if the app ID fulfills the expected format and contains a hashed bundle ID, NO
  464. * otherwise.
  465. */
  466. - (BOOL)isAppIDValid {
  467. NSString *appID = _options.googleAppID;
  468. BOOL isValid = [FIRApp validateAppID:appID];
  469. if (!isValid) {
  470. NSString *expectedBundleID = [self expectedBundleID];
  471. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  472. @"The GOOGLE_APP_ID either in the plist file "
  473. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  474. @"the plist file, use the iOS version of bundle identifier to download the file, "
  475. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  476. @"identifier to '%@'. Or you can download a new configuration file that matches "
  477. @"your bundle identifier from %@ and replace the current one.",
  478. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  479. };
  480. return isValid;
  481. }
  482. + (BOOL)validateAppID:(NSString *)appID {
  483. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  484. // have a valid hashed bundle ID, otherwise we just warn about the potential issue.
  485. if (!appID.length) {
  486. return NO;
  487. }
  488. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  489. stringScanner.charactersToBeSkipped = nil;
  490. NSString *appIDVersion;
  491. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  492. intoString:&appIDVersion]) {
  493. return NO;
  494. }
  495. if (![stringScanner scanString:@":" intoString:NULL]) {
  496. // appIDVersion must be separated by ":"
  497. return NO;
  498. }
  499. NSArray *knownVersions = @[ @"1" ];
  500. if (![knownVersions containsObject:appIDVersion]) {
  501. // Permit unknown yet properly formatted app ID versions.
  502. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  503. return YES;
  504. }
  505. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  506. return NO;
  507. }
  508. if (![self validateBundleIDHashWithinAppID:appID forVersion:appIDVersion]) {
  509. return NO;
  510. }
  511. return YES;
  512. }
  513. + (NSString *)actualBundleID {
  514. return [[NSBundle mainBundle] bundleIdentifier];
  515. }
  516. /**
  517. * Validates that the format of the app ID string is what is expected based on the supplied version.
  518. * The version must end in ":".
  519. *
  520. * For v1 app ids the format is expected to be
  521. * '<version #>:<project number>:ios:<hashed bundle id>'.
  522. *
  523. * This method does not verify that the contents of the app id are correct, just that they fulfill
  524. * the expected format.
  525. *
  526. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  527. * @param version Indicates what version of the app id format this string should be.
  528. * @return YES if provided string fulfills the expected format, NO otherwise.
  529. */
  530. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  531. if (!appID.length || !version.length) {
  532. return NO;
  533. }
  534. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  535. stringScanner.charactersToBeSkipped = nil;
  536. // Skip version part
  537. // '*<version #>*:<project number>:ios:<hashed bundle id>'
  538. if (![stringScanner scanString:version intoString:NULL]) {
  539. // The version part is missing or mismatched
  540. return NO;
  541. }
  542. // Validate version part (see part between '*' symbols below)
  543. // '<version #>*:*<project number>:ios:<hashed bundle id>'
  544. if (![stringScanner scanString:@":" intoString:NULL]) {
  545. // appIDVersion must be separated by ":"
  546. return NO;
  547. }
  548. // Validate version part (see part between '*' symbols below)
  549. // '<version #>:*<project number>*:ios:<hashed bundle id>'.
  550. NSInteger projectNumber = NSNotFound;
  551. if (![stringScanner scanInteger:&projectNumber]) {
  552. // NO project number found.
  553. return NO;
  554. }
  555. // Validate version part (see part between '*' symbols below)
  556. // '<version #>:<project number>*:*ios:<hashed bundle id>'.
  557. if (![stringScanner scanString:@":" intoString:NULL]) {
  558. // The project number must be separated by ":"
  559. return NO;
  560. }
  561. // Validate version part (see part between '*' symbols below)
  562. // '<version #>:<project number>:*ios*:<hashed bundle id>'.
  563. NSString *platform;
  564. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  565. return NO;
  566. }
  567. if (![platform isEqualToString:@"ios"]) {
  568. // The platform must be @"ios"
  569. return NO;
  570. }
  571. // Validate version part (see part between '*' symbols below)
  572. // '<version #>:<project number>:ios*:*<hashed bundle id>'.
  573. if (![stringScanner scanString:@":" intoString:NULL]) {
  574. // The platform must be separated by ":"
  575. return NO;
  576. }
  577. // Validate version part (see part between '*' symbols below)
  578. // '<version #>:<project number>:ios:*<hashed bundle id>*'.
  579. unsigned long long bundleIDHash = NSNotFound;
  580. if (![stringScanner scanHexLongLong:&bundleIDHash]) {
  581. // Hashed bundleID part is missing
  582. return NO;
  583. }
  584. if (!stringScanner.isAtEnd) {
  585. // There are not allowed characters in the hashed bundle ID part
  586. return NO;
  587. }
  588. return YES;
  589. }
  590. /**
  591. * Validates that the hashed bundle ID included in the app ID string is what is expected based on
  592. * the supplied version.
  593. *
  594. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  595. *
  596. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  597. * @param version Indicates what version of the app id format this string should be.
  598. * @return YES if provided string fulfills the expected hashed bundle ID and the version is known,
  599. * NO otherwise.
  600. */
  601. + (BOOL)validateBundleIDHashWithinAppID:(NSString *)appID forVersion:(NSString *)version {
  602. // Extract the hashed bundle ID from the given app ID.
  603. // This assumes the app ID format is the same for all known versions below.
  604. // If the app ID format changes in future versions, the tokenizing of the app
  605. // ID format will need to take into account the version of the app ID.
  606. NSArray *components = [appID componentsSeparatedByString:@":"];
  607. if (components.count != 4) {
  608. return NO;
  609. }
  610. NSString *suppliedBundleIDHashString = components[3];
  611. if (!suppliedBundleIDHashString.length) {
  612. return NO;
  613. }
  614. uint64_t suppliedBundleIDHash;
  615. NSScanner *scanner = [NSScanner scannerWithString:suppliedBundleIDHashString];
  616. if (![scanner scanHexLongLong:&suppliedBundleIDHash]) {
  617. return NO;
  618. }
  619. if ([version isEqual:@"1"]) {
  620. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  621. return YES;
  622. }
  623. // Unknown version.
  624. return NO;
  625. }
  626. - (NSString *)expectedBundleID {
  627. return _options.bundleID;
  628. }
  629. // end App ID validation
  630. #pragma mark - Reading From Plist & User Defaults
  631. /**
  632. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  633. * readability.
  634. */
  635. - (void)clearDataCollectionSwitchFromUserDefaults {
  636. NSString *key =
  637. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  638. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  639. }
  640. /**
  641. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  642. * readability.
  643. */
  644. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  645. // Read the object in user defaults, and only return if it's an NSNumber.
  646. NSString *key =
  647. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  648. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  649. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  650. return collectionEnabledDefaultsObject;
  651. }
  652. return nil;
  653. }
  654. /**
  655. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  656. * only read once from the plist and return the cached value.
  657. */
  658. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  659. static NSNumber *collectionEnabledPlistObject;
  660. static dispatch_once_t onceToken;
  661. dispatch_once(&onceToken, ^{
  662. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  663. id plistValue = [[NSBundle mainBundle]
  664. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  665. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  666. collectionEnabledPlistObject = (NSNumber *)plistValue;
  667. }
  668. });
  669. return collectionEnabledPlistObject;
  670. }
  671. #pragma mark - Swift Components.
  672. + (void)registerSwiftComponents {
  673. SEL componentsToRegisterSEL = @selector(componentsToRegister);
  674. // Dictionary of class names that conform to `FIRLibrary` and their user agents. These should only
  675. // be SDKs that are written in Swift but still visible to ObjC.
  676. // This is only necessary for products that need to do work at launch during configuration.
  677. NSDictionary<NSString *, NSString *> *swiftComponents = @{
  678. @"FIRSessions" : @"fire-ses",
  679. @"FIRAuthComponent" : @"fire-auth",
  680. };
  681. for (NSString *className in swiftComponents.allKeys) {
  682. Class klass = NSClassFromString(className);
  683. if (klass && [klass respondsToSelector:componentsToRegisterSEL]) {
  684. [FIRApp registerInternalLibrary:klass withName:swiftComponents[className]];
  685. }
  686. }
  687. // Swift libraries that don't need component behaviour
  688. NSDictionary<NSString *, NSString *> *swiftLibraries = @{
  689. @"FIRCombineAuthLibrary" : @"comb-auth",
  690. @"FIRCombineFirestoreLibrary" : @"comb-firestore",
  691. @"FIRCombineFunctionsLibrary" : @"comb-functions",
  692. @"FIRCombineStorageLibrary" : @"comb-storage",
  693. @"FIRFunctions" : @"fire-fun",
  694. @"FIRStorage" : @"fire-str",
  695. @"FIRVertexAIComponent" : @"fire-vertex",
  696. @"FIRDataConnectComponent" : @"fire-dc",
  697. };
  698. for (NSString *className in swiftLibraries.allKeys) {
  699. Class klass = NSClassFromString(className);
  700. if (klass) {
  701. NSString *version = FIRFirebaseVersion();
  702. #pragma clang diagnostic push
  703. #pragma clang diagnostic ignored "-Wundeclared-selector"
  704. SEL sdkVersionSelector = @selector(sdkVersion);
  705. #pragma clang diagnostic pop
  706. if ([klass respondsToSelector:sdkVersionSelector]) {
  707. #pragma clang diagnostic push
  708. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  709. NSString *sdkVersion = (NSString *)[klass performSelector:sdkVersionSelector];
  710. if (sdkVersion) version = sdkVersion;
  711. #pragma clang diagnostic pop
  712. }
  713. [FIRApp registerLibrary:swiftLibraries[className] withVersion:version];
  714. }
  715. }
  716. }
  717. #pragma mark - App Life Cycle
  718. - (void)subscribeForAppDidBecomeActiveNotifications {
  719. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  720. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  721. #elif TARGET_OS_OSX
  722. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  723. #elif TARGET_OS_WATCH
  724. // TODO(ncooke3): Remove when minimum supported watchOS version is watchOS 7.0.
  725. // On watchOS 7.0+, heartbeats are logged when the watch app becomes active.
  726. // On watchOS 6.0, heartbeats are logged when the Firebase app is configuring.
  727. // While it does not cover all use cases, logging when the Firebase app is
  728. // configuring is done because watchOS lifecycle notifications are a
  729. // watchOS 7.0+ feature.
  730. NSNotificationName notificationName = kFIRAppReadyToConfigureSDKNotification;
  731. if (@available(watchOS 7.0, *)) {
  732. notificationName = WKApplicationDidBecomeActiveNotification;
  733. }
  734. #endif
  735. [[NSNotificationCenter defaultCenter] addObserver:self
  736. selector:@selector(appDidBecomeActive:)
  737. name:notificationName
  738. object:nil];
  739. }
  740. - (void)appDidBecomeActive:(NSNotification *)notification {
  741. if ([self isDataCollectionDefaultEnabled]) {
  742. // If changing the below line, consult with the Games team to ensure they
  743. // are not negatively impacted. For more details, see
  744. // go/firebase-game-sdk-user-agent-register-timing.
  745. [self.heartbeatLogger log];
  746. }
  747. }
  748. #if DEBUG
  749. + (void)findMisnamedGoogleServiceInfoPlist {
  750. for (NSBundle *bundle in [NSBundle allBundles]) {
  751. // Not recursive, but we're looking for misnames, not people accidentally
  752. // hiding their config file in a subdirectory of their bundle.
  753. NSArray *plistPaths = [bundle pathsForResourcesOfType:@"plist" inDirectory:nil];
  754. for (NSString *path in plistPaths) {
  755. @autoreleasepool {
  756. NSDictionary<NSString *, id> *contents = [NSDictionary dictionaryWithContentsOfFile:path];
  757. if (contents == nil) {
  758. continue;
  759. }
  760. NSString *projectID = contents[@"PROJECT_ID"];
  761. if (projectID != nil) {
  762. [NSException raise:kFirebaseCoreErrorDomain
  763. format:@"`FirebaseApp.configure()` could not find the default "
  764. @"configuration plist in your project, but did find one at "
  765. @"%@. Please rename this file to GoogleService-Info.plist to "
  766. @"use it as the default configuration.",
  767. path];
  768. }
  769. }
  770. }
  771. }
  772. }
  773. #endif // DEBUG
  774. @end