FIRApp.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. + (NSError *)errorForMissingOptions {
  390. NSDictionary *errorDict = @{
  391. NSLocalizedDescriptionKey :
  392. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  393. NSLocalizedRecoverySuggestionErrorKey :
  394. @"Check formatting and location of GoogleService-Info.plist."
  395. };
  396. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-100 userInfo:errorDict];
  397. }
  398. + (NSError *)errorForInvalidAppID {
  399. NSDictionary *errorDict = @{
  400. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  401. NSLocalizedRecoverySuggestionErrorKey :
  402. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  403. @"customized options."
  404. };
  405. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-101 userInfo:errorDict];
  406. }
  407. + (BOOL)isDefaultAppConfigured {
  408. return (sDefaultApp != nil);
  409. }
  410. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  411. // Create the set of characters which aren't allowed, only if this feature is used.
  412. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  413. [allowedSet addCharactersInString:@"-_."];
  414. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  415. // Make sure the library name and version strings do not contain unexpected characters, and
  416. // add the name/version pair to the dictionary.
  417. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  418. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  419. [[self userAgent] setValue:version forComponent:name];
  420. } else {
  421. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  422. @"The library name (%@) or version number (%@) contain invalid characters. "
  423. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  424. name, version);
  425. }
  426. }
  427. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  428. withName:(nonnull NSString *)name {
  429. [self registerInternalLibrary:library withName:name withVersion:FIRFirebaseVersion()];
  430. }
  431. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  432. withName:(nonnull NSString *)name
  433. withVersion:(nonnull NSString *)version {
  434. // This is called at +load time, keep the work to a minimum.
  435. // Ensure the class given conforms to the proper protocol.
  436. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  437. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  438. [NSException raise:NSInvalidArgumentException
  439. format:@"Class %@ attempted to register components, but it does not conform to "
  440. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  441. library];
  442. }
  443. [FIRComponentContainer registerAsComponentRegistrant:library];
  444. [self registerLibrary:name withVersion:version];
  445. }
  446. + (FIRFirebaseUserAgent *)userAgent {
  447. static dispatch_once_t onceToken;
  448. static FIRFirebaseUserAgent *_userAgent;
  449. dispatch_once(&onceToken, ^{
  450. _userAgent = [[FIRFirebaseUserAgent alloc] init];
  451. [_userAgent setValue:FIRFirebaseVersion() forComponent:@"fire-ios"];
  452. });
  453. return _userAgent;
  454. }
  455. + (NSString *)firebaseUserAgent {
  456. return [[self userAgent] firebaseUserAgent];
  457. }
  458. - (void)checkExpectedBundleID {
  459. NSArray *bundles = [FIRBundleUtil relevantBundles];
  460. NSString *expectedBundleID = [self expectedBundleID];
  461. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  462. // backward compatibility.
  463. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  464. inBundles:bundles]) {
  465. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  466. @"The project's Bundle ID is inconsistent with "
  467. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  468. @"using a customized options. To ensure that everything can be configured "
  469. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  470. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  471. @"download a new configuration file that matches your bundle identifier from %@ "
  472. @"and replace the current one.",
  473. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  474. }
  475. }
  476. #pragma mark - private - App ID Validation
  477. /**
  478. * Validates the format of app ID and its included bundle ID hash contained in GOOGLE_APP_ID in the
  479. * plist file. This is the main method for validating app ID.
  480. *
  481. * @return YES if the app ID fulfills the expected format and contains a hashed bundle ID, NO
  482. * otherwise.
  483. */
  484. - (BOOL)isAppIDValid {
  485. NSString *appID = _options.googleAppID;
  486. BOOL isValid = [FIRApp validateAppID:appID];
  487. if (!isValid) {
  488. NSString *expectedBundleID = [self expectedBundleID];
  489. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  490. @"The GOOGLE_APP_ID either in the plist file "
  491. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  492. @"the plist file, use the iOS version of bundle identifier to download the file, "
  493. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  494. @"identifier to '%@'. Or you can download a new configuration file that matches "
  495. @"your bundle identifier from %@ and replace the current one.",
  496. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  497. };
  498. return isValid;
  499. }
  500. + (BOOL)validateAppID:(NSString *)appID {
  501. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  502. // have a valid hashed bundle ID, otherwise we just warn about the potential issue.
  503. if (!appID.length) {
  504. return NO;
  505. }
  506. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  507. stringScanner.charactersToBeSkipped = nil;
  508. NSString *appIDVersion;
  509. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  510. intoString:&appIDVersion]) {
  511. return NO;
  512. }
  513. if (![stringScanner scanString:@":" intoString:NULL]) {
  514. // appIDVersion must be separated by ":"
  515. return NO;
  516. }
  517. NSArray *knownVersions = @[ @"1" ];
  518. if (![knownVersions containsObject:appIDVersion]) {
  519. // Permit unknown yet properly formatted app ID versions.
  520. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  521. return YES;
  522. }
  523. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  524. return NO;
  525. }
  526. if (![self validateBundleIDHashWithinAppID:appID forVersion:appIDVersion]) {
  527. return NO;
  528. }
  529. return YES;
  530. }
  531. + (NSString *)actualBundleID {
  532. return [[NSBundle mainBundle] bundleIdentifier];
  533. }
  534. /**
  535. * Validates that the format of the app ID string is what is expected based on the supplied version.
  536. * The version must end in ":".
  537. *
  538. * For v1 app ids the format is expected to be
  539. * '<version #>:<project number>:ios:<hashed bundle id>'.
  540. *
  541. * This method does not verify that the contents of the app id are correct, just that they fulfill
  542. * the expected format.
  543. *
  544. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  545. * @param version Indicates what version of the app id format this string should be.
  546. * @return YES if provided string fulfills the expected format, NO otherwise.
  547. */
  548. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  549. if (!appID.length || !version.length) {
  550. return NO;
  551. }
  552. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  553. stringScanner.charactersToBeSkipped = nil;
  554. // Skip version part
  555. // '*<version #>*:<project number>:ios:<hashed bundle id>'
  556. if (![stringScanner scanString:version intoString:NULL]) {
  557. // The version part is missing or mismatched
  558. return NO;
  559. }
  560. // Validate version part (see part between '*' symbols below)
  561. // '<version #>*:*<project number>:ios:<hashed bundle id>'
  562. if (![stringScanner scanString:@":" intoString:NULL]) {
  563. // appIDVersion must be separated by ":"
  564. return NO;
  565. }
  566. // Validate version part (see part between '*' symbols below)
  567. // '<version #>:*<project number>*:ios:<hashed bundle id>'.
  568. NSInteger projectNumber = NSNotFound;
  569. if (![stringScanner scanInteger:&projectNumber]) {
  570. // NO project number found.
  571. return NO;
  572. }
  573. // Validate version part (see part between '*' symbols below)
  574. // '<version #>:<project number>*:*ios:<hashed bundle id>'.
  575. if (![stringScanner scanString:@":" intoString:NULL]) {
  576. // The project number must be separated by ":"
  577. return NO;
  578. }
  579. // Validate version part (see part between '*' symbols below)
  580. // '<version #>:<project number>:*ios*:<hashed bundle id>'.
  581. NSString *platform;
  582. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  583. return NO;
  584. }
  585. if (![platform isEqualToString:@"ios"]) {
  586. // The platform must be @"ios"
  587. return NO;
  588. }
  589. // Validate version part (see part between '*' symbols below)
  590. // '<version #>:<project number>:ios*:*<hashed bundle id>'.
  591. if (![stringScanner scanString:@":" intoString:NULL]) {
  592. // The platform must be separated by ":"
  593. return NO;
  594. }
  595. // Validate version part (see part between '*' symbols below)
  596. // '<version #>:<project number>:ios:*<hashed bundle id>*'.
  597. unsigned long long bundleIDHash = NSNotFound;
  598. if (![stringScanner scanHexLongLong:&bundleIDHash]) {
  599. // Hashed bundleID part is missing
  600. return NO;
  601. }
  602. if (!stringScanner.isAtEnd) {
  603. // There are not allowed characters in the hashed bundle ID part
  604. return NO;
  605. }
  606. return YES;
  607. }
  608. /**
  609. * Validates that the hashed bundle ID included in the app ID string is what is expected based on
  610. * the supplied version.
  611. *
  612. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  613. *
  614. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  615. * @param version Indicates what version of the app id format this string should be.
  616. * @return YES if provided string fulfills the expected hashed bundle ID and the version is known,
  617. * NO otherwise.
  618. */
  619. + (BOOL)validateBundleIDHashWithinAppID:(NSString *)appID forVersion:(NSString *)version {
  620. // Extract the hashed bundle ID from the given app ID.
  621. // This assumes the app ID format is the same for all known versions below.
  622. // If the app ID format changes in future versions, the tokenizing of the app
  623. // ID format will need to take into account the version of the app ID.
  624. NSArray *components = [appID componentsSeparatedByString:@":"];
  625. if (components.count != 4) {
  626. return NO;
  627. }
  628. NSString *suppliedBundleIDHashString = components[3];
  629. if (!suppliedBundleIDHashString.length) {
  630. return NO;
  631. }
  632. uint64_t suppliedBundleIDHash;
  633. NSScanner *scanner = [NSScanner scannerWithString:suppliedBundleIDHashString];
  634. if (![scanner scanHexLongLong:&suppliedBundleIDHash]) {
  635. return NO;
  636. }
  637. if ([version isEqual:@"1"]) {
  638. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  639. return YES;
  640. }
  641. // Unknown version.
  642. return NO;
  643. }
  644. - (NSString *)expectedBundleID {
  645. return _options.bundleID;
  646. }
  647. // end App ID validation
  648. #pragma mark - Reading From Plist & User Defaults
  649. /**
  650. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  651. * readability.
  652. */
  653. - (void)clearDataCollectionSwitchFromUserDefaults {
  654. NSString *key =
  655. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  656. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  657. }
  658. /**
  659. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  660. * readability.
  661. */
  662. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  663. // Read the object in user defaults, and only return if it's an NSNumber.
  664. NSString *key =
  665. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  666. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  667. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  668. return collectionEnabledDefaultsObject;
  669. }
  670. return nil;
  671. }
  672. /**
  673. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  674. * only read once from the plist and return the cached value.
  675. */
  676. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  677. static NSNumber *collectionEnabledPlistObject;
  678. static dispatch_once_t onceToken;
  679. dispatch_once(&onceToken, ^{
  680. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  681. id plistValue = [[NSBundle mainBundle]
  682. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  683. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  684. collectionEnabledPlistObject = (NSNumber *)plistValue;
  685. }
  686. });
  687. return collectionEnabledPlistObject;
  688. }
  689. #pragma mark - Swift Components.
  690. + (void)registerSwiftComponents {
  691. SEL componentsToRegisterSEL = @selector(componentsToRegister);
  692. // Dictionary of class names that conform to `FIRLibrary` and their user agents. These should only
  693. // be SDKs that are written in Swift but still visible to ObjC.
  694. // This is only necessary for products that need to do work at launch during configuration.
  695. NSDictionary<NSString *, NSString *> *swiftComponents = @{
  696. @"FIRSessions" : @"fire-ses",
  697. @"FIRAuthComponent" : @"fire-auth",
  698. };
  699. for (NSString *className in swiftComponents.allKeys) {
  700. Class klass = NSClassFromString(className);
  701. if (klass && [klass respondsToSelector:componentsToRegisterSEL]) {
  702. [FIRApp registerInternalLibrary:klass withName:swiftComponents[className]];
  703. }
  704. }
  705. // Swift libraries that don't need component behaviour
  706. NSDictionary<NSString *, NSString *> *swiftLibraries = @{
  707. @"FIRCombineAuthLibrary" : @"comb-auth",
  708. @"FIRCombineFirestoreLibrary" : @"comb-firestore",
  709. @"FIRCombineFunctionsLibrary" : @"comb-functions",
  710. @"FIRCombineStorageLibrary" : @"comb-storage",
  711. @"FIRFunctions" : @"fire-fun",
  712. @"FIRStorage" : @"fire-str",
  713. @"FIRVertexAIComponent" : @"fire-vertex",
  714. @"FIRDataConnectComponent" : @"fire-dc",
  715. };
  716. for (NSString *className in swiftLibraries.allKeys) {
  717. Class klass = NSClassFromString(className);
  718. if (klass) {
  719. NSString *version = FIRFirebaseVersion();
  720. #pragma clang diagnostic push
  721. #pragma clang diagnostic ignored "-Wundeclared-selector"
  722. SEL sdkVersionSelector = @selector(sdkVersion);
  723. #pragma clang diagnostic pop
  724. if ([klass respondsToSelector:sdkVersionSelector]) {
  725. #pragma clang diagnostic push
  726. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  727. NSString *sdkVersion = (NSString *)[klass performSelector:sdkVersionSelector];
  728. if (sdkVersion) version = sdkVersion;
  729. #pragma clang diagnostic pop
  730. }
  731. [FIRApp registerLibrary:swiftLibraries[className] withVersion:version];
  732. }
  733. }
  734. }
  735. #pragma mark - App Life Cycle
  736. - (void)subscribeForAppDidBecomeActiveNotifications {
  737. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  738. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  739. #elif TARGET_OS_OSX
  740. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  741. #elif TARGET_OS_WATCH
  742. // TODO(ncooke3): Remove when minimum supported watchOS version is watchOS 7.0.
  743. // On watchOS 7.0+, heartbeats are logged when the watch app becomes active.
  744. // On watchOS 6.0, heartbeats are logged when the Firebase app is configuring.
  745. // While it does not cover all use cases, logging when the Firebase app is
  746. // configuring is done because watchOS lifecycle notifications are a
  747. // watchOS 7.0+ feature.
  748. NSNotificationName notificationName = kFIRAppReadyToConfigureSDKNotification;
  749. if (@available(watchOS 7.0, *)) {
  750. notificationName = WKApplicationDidBecomeActiveNotification;
  751. }
  752. #endif
  753. [[NSNotificationCenter defaultCenter] addObserver:self
  754. selector:@selector(appDidBecomeActive:)
  755. name:notificationName
  756. object:nil];
  757. }
  758. - (void)appDidBecomeActive:(NSNotification *)notification {
  759. if ([self isDataCollectionDefaultEnabled]) {
  760. // If changing the below line, consult with the Games team to ensure they
  761. // are not negatively impacted. For more details, see
  762. // go/firebase-game-sdk-user-agent-register-timing.
  763. [self.heartbeatLogger log];
  764. }
  765. }
  766. #if DEBUG
  767. + (void)findMisnamedGoogleServiceInfoPlist {
  768. for (NSBundle *bundle in [NSBundle allBundles]) {
  769. // Not recursive, but we're looking for misnames, not people accidentally
  770. // hiding their config file in a subdirectory of their bundle.
  771. NSArray *plistPaths = [bundle pathsForResourcesOfType:@"plist" inDirectory:nil];
  772. for (NSString *path in plistPaths) {
  773. @autoreleasepool {
  774. NSDictionary<NSString *, id> *contents = [NSDictionary dictionaryWithContentsOfFile:path];
  775. if (contents == nil) {
  776. continue;
  777. }
  778. NSString *projectID = contents[@"PROJECT_ID"];
  779. if (projectID != nil) {
  780. [NSException raise:kFirebaseCoreErrorDomain
  781. format:@"`FirebaseApp.configure()` could not find the default "
  782. @"configuration plist in your project, but did find one at "
  783. @"%@. Please rename this file to GoogleService-Info.plist to "
  784. @"use it as the default configuration.",
  785. path];
  786. }
  787. }
  788. }
  789. }
  790. }
  791. #endif // DEBUG
  792. @end