FIRApp.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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 subscribeForAppDidBecomeActiveNotifications];
  328. return YES;
  329. }
  330. - (FIROptions *)options {
  331. return [_options copy];
  332. }
  333. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  334. #ifdef DEBUG
  335. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  336. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  337. self.alreadyOutputDataCollectionFlag = YES;
  338. #endif // DEBUG
  339. NSString *key =
  340. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  341. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  342. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  343. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  344. // default app, so return if this isn't the default app.
  345. if (!self.isDefaultApp) {
  346. return;
  347. }
  348. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  349. if ([self.options isAnalyticsCollectionExplicitlySet]) {
  350. return;
  351. }
  352. // The Analytics flag has not been explicitly set, so update with the value being set.
  353. #pragma clang diagnostic push
  354. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  355. [[FIRAnalyticsConfiguration sharedInstance]
  356. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  357. persistSetting:NO];
  358. #pragma clang diagnostic pop
  359. }
  360. - (BOOL)isDataCollectionDefaultEnabled {
  361. // Check if it's been manually set before in code, and use that as the higher priority value.
  362. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  363. if (defaultsObject != nil) {
  364. #ifdef DEBUG
  365. if (!self.alreadyOutputDataCollectionFlag) {
  366. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  367. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  368. self.alreadyOutputDataCollectionFlag = YES;
  369. }
  370. #endif // DEBUG
  371. return [defaultsObject boolValue];
  372. }
  373. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  374. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  375. // no performance impact calling multiple times.
  376. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  377. if (collectionEnabledPlistValue != nil) {
  378. #ifdef DEBUG
  379. if (!self.alreadyOutputDataCollectionFlag) {
  380. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  381. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  382. self.alreadyOutputDataCollectionFlag = YES;
  383. }
  384. #endif // DEBUG
  385. return [collectionEnabledPlistValue boolValue];
  386. }
  387. #ifdef DEBUG
  388. if (!self.alreadyOutputDataCollectionFlag) {
  389. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  390. self.alreadyOutputDataCollectionFlag = YES;
  391. }
  392. #endif // DEBUG
  393. return YES;
  394. }
  395. #pragma mark - private
  396. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  397. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  398. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  399. NSDictionary *appInfoDict = @{
  400. kFIRAppNameKey : app.name,
  401. kFIRAppIsDefaultAppKey : isDefaultApp,
  402. kFIRGoogleAppIDKey : app.options.googleAppID
  403. };
  404. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  405. object:self
  406. userInfo:appInfoDict];
  407. // This is the new way of sending information to SDKs.
  408. // TODO: Do we want this on a background thread, maybe?
  409. @synchronized(self) {
  410. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  411. [library configureWithApp:app];
  412. }
  413. }
  414. }
  415. + (NSError *)errorForMissingOptions {
  416. NSDictionary *errorDict = @{
  417. NSLocalizedDescriptionKey :
  418. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  419. NSLocalizedRecoverySuggestionErrorKey :
  420. @"Check formatting and location of GoogleService-Info.plist."
  421. };
  422. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-100 userInfo:errorDict];
  423. }
  424. + (NSError *)errorForInvalidAppID {
  425. NSDictionary *errorDict = @{
  426. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  427. NSLocalizedRecoverySuggestionErrorKey :
  428. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  429. @"customized options."
  430. };
  431. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-101 userInfo:errorDict];
  432. }
  433. + (BOOL)isDefaultAppConfigured {
  434. return (sDefaultApp != nil);
  435. }
  436. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  437. // Create the set of characters which aren't allowed, only if this feature is used.
  438. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  439. [allowedSet addCharactersInString:@"-_."];
  440. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  441. // Make sure the library name and version strings do not contain unexpected characters, and
  442. // add the name/version pair to the dictionary.
  443. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  444. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  445. [[self userAgent] setValue:version forComponent:name];
  446. } else {
  447. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  448. @"The library name (%@) or version number (%@) contain invalid characters. "
  449. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  450. name, version);
  451. }
  452. }
  453. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  454. withName:(nonnull NSString *)name {
  455. [self registerInternalLibrary:library withName:name withVersion:FIRFirebaseVersion()];
  456. }
  457. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  458. withName:(nonnull NSString *)name
  459. withVersion:(nonnull NSString *)version {
  460. // This is called at +load time, keep the work to a minimum.
  461. // Ensure the class given conforms to the proper protocol.
  462. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  463. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  464. [NSException raise:NSInvalidArgumentException
  465. format:@"Class %@ attempted to register components, but it does not conform to "
  466. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  467. library];
  468. }
  469. [FIRComponentContainer registerAsComponentRegistrant:library];
  470. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  471. static dispatch_once_t onceToken;
  472. dispatch_once(&onceToken, ^{
  473. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  474. });
  475. @synchronized(self) {
  476. [sRegisteredAsConfigurable addObject:library];
  477. }
  478. }
  479. [self registerLibrary:name withVersion:version];
  480. }
  481. + (FIRFirebaseUserAgent *)userAgent {
  482. static dispatch_once_t onceToken;
  483. static FIRFirebaseUserAgent *_userAgent;
  484. dispatch_once(&onceToken, ^{
  485. _userAgent = [[FIRFirebaseUserAgent alloc] init];
  486. [_userAgent setValue:FIRFirebaseVersion() forComponent:@"fire-ios"];
  487. });
  488. return _userAgent;
  489. }
  490. + (NSString *)firebaseUserAgent {
  491. return [[self userAgent] firebaseUserAgent];
  492. }
  493. - (void)checkExpectedBundleID {
  494. NSArray *bundles = [FIRBundleUtil relevantBundles];
  495. NSString *expectedBundleID = [self expectedBundleID];
  496. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  497. // backward compatibility.
  498. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  499. inBundles:bundles]) {
  500. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  501. @"The project's Bundle ID is inconsistent with "
  502. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  503. @"using a customized options. To ensure that everything can be configured "
  504. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  505. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  506. @"download a new configuration file that matches your bundle identifier from %@ "
  507. @"and replace the current one.",
  508. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  509. }
  510. }
  511. #pragma mark - private - App ID Validation
  512. /**
  513. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  514. * This is the main method for validating app ID.
  515. *
  516. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  517. */
  518. - (BOOL)isAppIDValid {
  519. NSString *appID = _options.googleAppID;
  520. BOOL isValid = [FIRApp validateAppID:appID];
  521. if (!isValid) {
  522. NSString *expectedBundleID = [self expectedBundleID];
  523. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  524. @"The GOOGLE_APP_ID either in the plist file "
  525. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  526. @"the plist file, use the iOS version of bundle identifier to download the file, "
  527. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  528. @"identifier to '%@'. Or you can download a new configuration file that matches "
  529. @"your bundle identifier from %@ and replace the current one.",
  530. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  531. };
  532. return isValid;
  533. }
  534. + (BOOL)validateAppID:(NSString *)appID {
  535. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  536. // have a valid fingerprint, otherwise we just warn about the potential issue.
  537. if (!appID.length) {
  538. return NO;
  539. }
  540. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  541. stringScanner.charactersToBeSkipped = nil;
  542. NSString *appIDVersion;
  543. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  544. intoString:&appIDVersion]) {
  545. return NO;
  546. }
  547. if (![stringScanner scanString:@":" intoString:NULL]) {
  548. // appIDVersion must be separated by ":"
  549. return NO;
  550. }
  551. NSArray *knownVersions = @[ @"1" ];
  552. if (![knownVersions containsObject:appIDVersion]) {
  553. // Permit unknown yet properly formatted app ID versions.
  554. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  555. return YES;
  556. }
  557. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  558. return NO;
  559. }
  560. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  561. return NO;
  562. }
  563. return YES;
  564. }
  565. + (NSString *)actualBundleID {
  566. return [[NSBundle mainBundle] bundleIdentifier];
  567. }
  568. /**
  569. * Validates that the format of the app ID string is what is expected based on the supplied version.
  570. * The version must end in ":".
  571. *
  572. * For v1 app ids the format is expected to be
  573. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  574. *
  575. * This method does not verify that the contents of the app id are correct, just that they fulfill
  576. * the expected format.
  577. *
  578. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  579. * @param version Indicates what version of the app id format this string should be.
  580. * @return YES if provided string fufills the expected format, NO otherwise.
  581. */
  582. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  583. if (!appID.length || !version.length) {
  584. return NO;
  585. }
  586. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  587. stringScanner.charactersToBeSkipped = nil;
  588. // Skip version part
  589. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  590. if (![stringScanner scanString:version intoString:NULL]) {
  591. // The version part is missing or mismatched
  592. return NO;
  593. }
  594. // Validate version part (see part between '*' symbols below)
  595. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  596. if (![stringScanner scanString:@":" intoString:NULL]) {
  597. // appIDVersion must be separated by ":"
  598. return NO;
  599. }
  600. // Validate version part (see part between '*' symbols below)
  601. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  602. NSInteger projectNumber = NSNotFound;
  603. if (![stringScanner scanInteger:&projectNumber]) {
  604. // NO project number found.
  605. return NO;
  606. }
  607. // Validate version part (see part between '*' symbols below)
  608. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  609. if (![stringScanner scanString:@":" intoString:NULL]) {
  610. // The project number must be separated by ":"
  611. return NO;
  612. }
  613. // Validate version part (see part between '*' symbols below)
  614. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  615. NSString *platform;
  616. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  617. return NO;
  618. }
  619. if (![platform isEqualToString:@"ios"]) {
  620. // The platform must be @"ios"
  621. return NO;
  622. }
  623. // Validate version part (see part between '*' symbols below)
  624. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  625. if (![stringScanner scanString:@":" intoString:NULL]) {
  626. // The platform must be separated by ":"
  627. return NO;
  628. }
  629. // Validate version part (see part between '*' symbols below)
  630. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  631. unsigned long long fingerprint = NSNotFound;
  632. if (![stringScanner scanHexLongLong:&fingerprint]) {
  633. // Fingerprint part is missing
  634. return NO;
  635. }
  636. if (!stringScanner.isAtEnd) {
  637. // There are not allowed characters in the fingerprint part
  638. return NO;
  639. }
  640. return YES;
  641. }
  642. /**
  643. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  644. * version.
  645. *
  646. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  647. *
  648. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  649. * @param version Indicates what version of the app id format this string should be.
  650. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  651. * otherwise.
  652. */
  653. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  654. // Extract the supplied fingerprint from the supplied app ID.
  655. // This assumes the app ID format is the same for all known versions below. If the app ID format
  656. // changes in future versions, the tokenizing of the app ID format will need to take into account
  657. // the version of the app ID.
  658. NSArray *components = [appID componentsSeparatedByString:@":"];
  659. if (components.count != 4) {
  660. return NO;
  661. }
  662. NSString *suppliedFingerprintString = components[3];
  663. if (!suppliedFingerprintString.length) {
  664. return NO;
  665. }
  666. uint64_t suppliedFingerprint;
  667. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  668. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  669. return NO;
  670. }
  671. if ([version isEqual:@"1"]) {
  672. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  673. return YES;
  674. }
  675. // Unknown version.
  676. return NO;
  677. }
  678. - (NSString *)expectedBundleID {
  679. return _options.bundleID;
  680. }
  681. // end App ID validation
  682. #pragma mark - Reading From Plist & User Defaults
  683. /**
  684. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  685. * readability.
  686. */
  687. - (void)clearDataCollectionSwitchFromUserDefaults {
  688. NSString *key =
  689. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  690. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  691. }
  692. /**
  693. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  694. * readability.
  695. */
  696. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  697. // Read the object in user defaults, and only return if it's an NSNumber.
  698. NSString *key =
  699. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  700. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  701. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  702. return collectionEnabledDefaultsObject;
  703. }
  704. return nil;
  705. }
  706. /**
  707. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  708. * only read once from the plist and return the cached value.
  709. */
  710. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  711. static NSNumber *collectionEnabledPlistObject;
  712. static dispatch_once_t onceToken;
  713. dispatch_once(&onceToken, ^{
  714. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  715. id plistValue = [[NSBundle mainBundle]
  716. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  717. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  718. collectionEnabledPlistObject = (NSNumber *)plistValue;
  719. }
  720. });
  721. return collectionEnabledPlistObject;
  722. }
  723. #pragma mark - Swift Components.
  724. + (void)registerSwiftComponents {
  725. SEL componentsToRegisterSEL = @selector(componentsToRegister);
  726. // Dictionary of class names that conform to `FIRLibrary` and their user agents. These should only
  727. // be SDKs that are written in Swift but still visible to ObjC.
  728. NSDictionary<NSString *, NSString *> *swiftComponents = @{
  729. @"FIRFunctionsComponent" : @"fire-fun",
  730. @"FIRStorageComponent" : @"fire-str",
  731. };
  732. for (NSString *className in swiftComponents.allKeys) {
  733. Class klass = NSClassFromString(className);
  734. if (klass && [klass respondsToSelector:componentsToRegisterSEL]) {
  735. [FIRApp registerInternalLibrary:klass withName:swiftComponents[className]];
  736. }
  737. }
  738. // Swift libraries that don't need component behaviour
  739. NSDictionary<NSString *, NSString *> *swiftLibraries = @{
  740. @"FIRCombineAuthLibrary" : @"comb-auth",
  741. @"FIRCombineFirestoreLibrary" : @"comb-firestore",
  742. @"FIRCombineFunctionsLibrary" : @"comb-functions",
  743. @"FIRCombineStorageLibrary" : @"comb-storage",
  744. };
  745. for (NSString *className in swiftLibraries.allKeys) {
  746. Class klass = NSClassFromString(className);
  747. if (klass) {
  748. [FIRApp registerLibrary:swiftLibraries[className] withVersion:FIRFirebaseVersion()];
  749. }
  750. }
  751. }
  752. #pragma mark - App Life Cycle
  753. - (void)subscribeForAppDidBecomeActiveNotifications {
  754. #if TARGET_OS_IOS || TARGET_OS_TV
  755. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  756. #elif TARGET_OS_OSX
  757. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  758. #endif
  759. #if !TARGET_OS_WATCH
  760. [[NSNotificationCenter defaultCenter] addObserver:self
  761. selector:@selector(appDidBecomeActive:)
  762. name:notificationName
  763. object:nil];
  764. #endif
  765. }
  766. - (void)appDidBecomeActive:(NSNotification *)notification {
  767. [self logCoreTelemetryIfEnabled];
  768. }
  769. - (void)logCoreTelemetryIfEnabled {
  770. if ([self isDataCollectionDefaultEnabled]) {
  771. [self.heartbeatLogger log];
  772. // TODO(ncooke3): Remove below code when CoreDiagnostics is removed.
  773. dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
  774. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:[self options]];
  775. });
  776. }
  777. }
  778. @end