FIRApp.m 34 KB

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