FIRApp.m 34 KB

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