FIRApp.m 33 KB

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