FIRApp.m 33 KB

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