FIRApp.m 33 KB

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