FIRApp.m 33 KB

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