FIRApp.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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/FIRVersion.h"
  27. #import "FirebaseCore/Sources/Private/FIRAppInternal.h"
  28. #import "FirebaseCore/Sources/Private/FIRCoreDiagnosticsConnector.h"
  29. #import "FirebaseCore/Sources/Private/FIRLibrary.h"
  30. #import "FirebaseCore/Sources/Private/FIRLogger.h"
  31. #import "FirebaseCore/Sources/Private/FIROptionsInternal.h"
  32. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  33. #import <objc/runtime.h>
  34. // The kFIRService strings are only here while transitioning CoreDiagnostics from the Analytics
  35. // pod to a Core dependency. These symbols are not used and should be deleted after the transition.
  36. NSString *const kFIRServiceAdMob;
  37. NSString *const kFIRServiceAuth;
  38. NSString *const kFIRServiceAuthUI;
  39. NSString *const kFIRServiceCrash;
  40. NSString *const kFIRServiceDatabase;
  41. NSString *const kFIRServiceDynamicLinks;
  42. NSString *const kFIRServiceFirestore;
  43. NSString *const kFIRServiceFunctions;
  44. NSString *const kFIRServiceInstanceID;
  45. NSString *const kFIRServiceInvites;
  46. NSString *const kFIRServiceMessaging;
  47. NSString *const kFIRServiceMeasurement;
  48. NSString *const kFIRServicePerformance;
  49. NSString *const kFIRServiceRemoteConfig;
  50. NSString *const kFIRServiceStorage;
  51. NSString *const kGGLServiceAnalytics;
  52. NSString *const kGGLServiceSignIn;
  53. NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT";
  54. NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification";
  55. NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification";
  56. NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey";
  57. NSString *const kFIRAppNameKey = @"FIRAppNameKey";
  58. NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey";
  59. NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat =
  60. @"/google/firebase/global_data_collection_enabled:%@";
  61. NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey =
  62. @"FirebaseDataCollectionDefaultEnabled";
  63. NSString *const kFIRAppDiagnosticsNotification = @"FIRAppDiagnosticsNotification";
  64. NSString *const kFIRAppDiagnosticsConfigurationTypeKey = @"ConfigType";
  65. NSString *const kFIRAppDiagnosticsErrorKey = @"Error";
  66. NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRApp";
  67. NSString *const kFIRAppDiagnosticsSDKNameKey = @"SDKName";
  68. NSString *const kFIRAppDiagnosticsSDKVersionKey = @"SDKVersion";
  69. NSString *const kFIRAppDiagnosticsApplePlatformPrefix = @"apple-platform";
  70. // Auth internal notification notification and key.
  71. NSString *const FIRAuthStateDidChangeInternalNotification =
  72. @"FIRAuthStateDidChangeInternalNotification";
  73. NSString *const FIRAuthStateDidChangeInternalNotificationAppKey =
  74. @"FIRAuthStateDidChangeInternalNotificationAppKey";
  75. NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey =
  76. @"FIRAuthStateDidChangeInternalNotificationTokenKey";
  77. NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey =
  78. @"FIRAuthStateDidChangeInternalNotificationUIDKey";
  79. /**
  80. * Error domain for exceptions and NSError construction.
  81. */
  82. NSString *const kFirebaseCoreErrorDomain = @"com.firebase.core";
  83. /**
  84. * The URL to download plist files.
  85. */
  86. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  87. /**
  88. * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle
  89. * events from Core.
  90. */
  91. static NSMutableArray<Class<FIRLibrary>> *sRegisteredAsConfigurable;
  92. @interface FIRApp ()
  93. #ifdef DEBUG
  94. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  95. #endif // DEBUG
  96. @end
  97. @implementation FIRApp
  98. // This is necessary since our custom getter prevents `_options` from being created.
  99. @synthesize options = _options;
  100. static NSMutableDictionary *sAllApps;
  101. static FIRApp *sDefaultApp;
  102. static NSMutableDictionary *sLibraryVersions;
  103. static dispatch_once_t sFirebaseUserAgentOnceToken;
  104. + (void)configure {
  105. FIROptions *options = [FIROptions defaultOptions];
  106. if (!options) {
  107. [NSException raise:kFirebaseCoreErrorDomain
  108. format:@"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find "
  109. @"a valid GoogleService-Info.plist in your project. Please download one "
  110. @"from %@.",
  111. kPlistURL];
  112. }
  113. [FIRApp configureWithOptions:options];
  114. #if TARGET_OS_OSX || TARGET_OS_TV
  115. FIRLogNotice(kFIRLoggerCore, @"I-COR000028",
  116. @"tvOS and macOS SDK support is not part of the official Firebase product. "
  117. @"Instead they are community supported. Details at "
  118. @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md.");
  119. #endif
  120. }
  121. + (void)configureWithOptions:(FIROptions *)options {
  122. if (!options) {
  123. [NSException raise:kFirebaseCoreErrorDomain
  124. format:@"Options is nil. Please pass a valid options."];
  125. }
  126. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  127. }
  128. + (NSCharacterSet *)applicationNameAllowedCharacters {
  129. static NSCharacterSet *applicationNameAllowedCharacters;
  130. static dispatch_once_t onceToken;
  131. dispatch_once(&onceToken, ^{
  132. NSMutableCharacterSet *allowedNameCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  133. [allowedNameCharacters addCharactersInString:@"-_"];
  134. applicationNameAllowedCharacters = [allowedNameCharacters copy];
  135. });
  136. return applicationNameAllowedCharacters;
  137. }
  138. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  139. if (!name || !options) {
  140. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  141. }
  142. if (name.length == 0) {
  143. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  144. }
  145. if ([name isEqualToString:kFIRDefaultAppName]) {
  146. if (sDefaultApp) {
  147. // The default app already exists. Handle duplicate `configure` calls and return.
  148. [self appWasConfiguredTwice:sDefaultApp usingOptions:options];
  149. return;
  150. }
  151. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  152. } else {
  153. // Validate the app name and ensure it hasn't been configured already.
  154. NSCharacterSet *nameCharacters = [NSCharacterSet characterSetWithCharactersInString:name];
  155. if (![[self applicationNameAllowedCharacters] isSupersetOfSet:nameCharacters]) {
  156. [NSException raise:kFirebaseCoreErrorDomain
  157. format:@"App name can only contain alphanumeric, "
  158. @"hyphen (-), and underscore (_) characters"];
  159. }
  160. @synchronized(self) {
  161. if (sAllApps && sAllApps[name]) {
  162. // The app already exists. Handle a duplicate `configure` call and return.
  163. [self appWasConfiguredTwice:sAllApps[name] usingOptions:options];
  164. return;
  165. }
  166. }
  167. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  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 `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your "
  216. @"application initialization. Read more: https://goo.gl/ctyzm8.");
  217. return nil;
  218. }
  219. + (FIRApp *)appNamed:(NSString *)name {
  220. @synchronized(self) {
  221. if (sAllApps) {
  222. FIRApp *app = sAllApps[name];
  223. if (app) {
  224. return app;
  225. }
  226. }
  227. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  228. return nil;
  229. }
  230. }
  231. + (NSDictionary *)allApps {
  232. @synchronized(self) {
  233. if (!sAllApps) {
  234. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  235. }
  236. return [sAllApps copy];
  237. }
  238. }
  239. // Public only for tests
  240. + (void)resetApps {
  241. @synchronized(self) {
  242. sDefaultApp = nil;
  243. [sAllApps removeAllObjects];
  244. sAllApps = nil;
  245. [sLibraryVersions removeAllObjects];
  246. sLibraryVersions = nil;
  247. sFirebaseUserAgentOnceToken = 0;
  248. }
  249. }
  250. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  251. @synchronized([self class]) {
  252. if (sAllApps && sAllApps[self.name]) {
  253. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  254. // Remove all registered libraries from the container to avoid creating new instances.
  255. [self.container removeAllComponents];
  256. // Remove all cached instances from the container before deleting the app.
  257. [self.container removeAllCachedInstances];
  258. [sAllApps removeObjectForKey:self.name];
  259. [self clearDataCollectionSwitchFromUserDefaults];
  260. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  261. sDefaultApp = nil;
  262. }
  263. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  264. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  265. object:[self class]
  266. userInfo:appInfoDict];
  267. completion(YES);
  268. } else {
  269. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  270. completion(NO);
  271. }
  272. }
  273. }
  274. + (void)addAppToAppDictionary:(FIRApp *)app {
  275. if (!sAllApps) {
  276. sAllApps = [NSMutableDictionary dictionary];
  277. }
  278. if ([app configureCore]) {
  279. sAllApps[app.name] = app;
  280. } else {
  281. [NSException raise:kFirebaseCoreErrorDomain
  282. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  283. @"GoogleService-Info.plist or set in the customized options."];
  284. }
  285. }
  286. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  287. self = [super init];
  288. if (self) {
  289. _name = [name copy];
  290. _options = [options copy];
  291. _options.editingLocked = YES;
  292. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  293. _container = [[FIRComponentContainer alloc] initWithApp:self];
  294. }
  295. return self;
  296. }
  297. - (void)dealloc {
  298. [[NSNotificationCenter defaultCenter] removeObserver:self];
  299. }
  300. - (BOOL)configureCore {
  301. [self checkExpectedBundleID];
  302. if (![self isAppIDValid]) {
  303. return NO;
  304. }
  305. [self logCoreTelemetryIfEnabled];
  306. #if TARGET_OS_IOS
  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. #endif
  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. @synchronized(self) {
  447. if (!sLibraryVersions) {
  448. sLibraryVersions = [[NSMutableDictionary alloc] init];
  449. }
  450. sLibraryVersions[name] = version;
  451. }
  452. } else {
  453. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  454. @"The library name (%@) or version number (%@) contain invalid characters. "
  455. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  456. name, version);
  457. }
  458. }
  459. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  460. withName:(nonnull NSString *)name
  461. withVersion:(nonnull NSString *)version {
  462. // This is called at +load time, keep the work to a minimum.
  463. // Ensure the class given conforms to the proper protocol.
  464. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  465. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  466. [NSException raise:NSInvalidArgumentException
  467. format:@"Class %@ attempted to register components, but it does not conform to "
  468. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  469. library];
  470. }
  471. [FIRComponentContainer registerAsComponentRegistrant:library];
  472. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  473. static dispatch_once_t onceToken;
  474. dispatch_once(&onceToken, ^{
  475. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  476. });
  477. @synchronized(self) {
  478. [sRegisteredAsConfigurable addObject:library];
  479. }
  480. }
  481. [self registerLibrary:name withVersion:version];
  482. }
  483. + (NSString *)firebaseUserAgent {
  484. @synchronized(self) {
  485. dispatch_once(&sFirebaseUserAgentOnceToken, ^{
  486. // Report FirebaseCore version for useragent string
  487. [FIRApp registerLibrary:@"fire-ios"
  488. withVersion:[NSString stringWithUTF8String:FIRCoreVersionString]];
  489. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  490. NSString *xcodeVersion = info[@"DTXcodeBuild"];
  491. NSString *sdkVersion = info[@"DTSDKBuild"];
  492. if (xcodeVersion) {
  493. [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion];
  494. }
  495. if (sdkVersion) {
  496. [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion];
  497. }
  498. NSString *swiftFlagValue = [self hasSwiftRuntime] ? @"true" : @"false";
  499. [FIRApp registerLibrary:@"swift" withVersion:swiftFlagValue];
  500. [FIRApp registerLibrary:kFIRAppDiagnosticsApplePlatformPrefix
  501. withVersion:[self applePlatform]];
  502. });
  503. NSMutableArray<NSString *> *libraries =
  504. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  505. for (NSString *libraryName in sLibraryVersions) {
  506. [libraries addObject:[NSString stringWithFormat:@"%@/%@", libraryName,
  507. sLibraryVersions[libraryName]]];
  508. }
  509. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  510. return [libraries componentsJoinedByString:@" "];
  511. }
  512. }
  513. + (BOOL)hasSwiftRuntime {
  514. // The class
  515. // [Swift._SwiftObject](https://github.com/apple/swift/blob/5eac3e2818eb340b11232aff83edfbd1c307fa03/stdlib/public/runtime/SwiftObject.h#L35)
  516. // is a part of Swift runtime, so it should be present if Swift runtime is available.
  517. BOOL hasSwiftRuntime =
  518. objc_lookUpClass("Swift._SwiftObject") != nil ||
  519. // Swift object class name before
  520. // https://github.com/apple/swift/commit/9637b4a6e11ddca72f5f6dbe528efc7c92f14d01
  521. objc_getClass("_TtCs12_SwiftObject") != nil;
  522. return hasSwiftRuntime;
  523. }
  524. + (NSString *)applePlatform {
  525. NSString *applePlatform = @"unknown";
  526. // When a Catalyst app is run on macOS then both `TARGET_OS_MACCATALYST` and `TARGET_OS_IOS` are
  527. // `true`, which means the condition list is order-sensitive.
  528. #if TARGET_OS_MACCATALYST
  529. applePlatform = @"maccatalyst";
  530. #elif TARGET_OS_IOS
  531. applePlatform = @"ios";
  532. #elif TARGET_OS_TV
  533. applePlatform = @"tvos";
  534. #elif TARGET_OS_OSX
  535. applePlatform = @"macos";
  536. #elif TARGET_OS_WATCH
  537. applePlatform = @"watchos";
  538. #endif
  539. return applePlatform;
  540. }
  541. - (void)checkExpectedBundleID {
  542. NSArray *bundles = [FIRBundleUtil relevantBundles];
  543. NSString *expectedBundleID = [self expectedBundleID];
  544. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  545. // backward compatibility.
  546. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  547. inBundles:bundles]) {
  548. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  549. @"The project's Bundle ID is inconsistent with "
  550. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  551. @"using a customized options. To ensure that everything can be configured "
  552. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  553. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  554. @"download a new configuration file that matches your bundle identifier from %@ "
  555. @"and replace the current one.",
  556. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  557. }
  558. }
  559. #pragma mark - private - App ID Validation
  560. /**
  561. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  562. * This is the main method for validating app ID.
  563. *
  564. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  565. */
  566. - (BOOL)isAppIDValid {
  567. NSString *appID = _options.googleAppID;
  568. BOOL isValid = [FIRApp validateAppID:appID];
  569. if (!isValid) {
  570. NSString *expectedBundleID = [self expectedBundleID];
  571. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  572. @"The GOOGLE_APP_ID either in the plist file "
  573. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  574. @"the plist file, use the iOS version of bundle identifier to download the file, "
  575. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  576. @"identifier to '%@'. Or you can download a new configuration file that matches "
  577. @"your bundle identifier from %@ and replace the current one.",
  578. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  579. };
  580. return isValid;
  581. }
  582. + (BOOL)validateAppID:(NSString *)appID {
  583. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  584. // have a valid fingerprint, otherwise we just warn about the potential issue.
  585. if (!appID.length) {
  586. return NO;
  587. }
  588. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  589. stringScanner.charactersToBeSkipped = nil;
  590. NSString *appIDVersion;
  591. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  592. intoString:&appIDVersion]) {
  593. return NO;
  594. }
  595. if (![stringScanner scanString:@":" intoString:NULL]) {
  596. // appIDVersion must be separated by ":"
  597. return NO;
  598. }
  599. NSArray *knownVersions = @[ @"1" ];
  600. if (![knownVersions containsObject:appIDVersion]) {
  601. // Permit unknown yet properly formatted app ID versions.
  602. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  603. return YES;
  604. }
  605. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  606. return NO;
  607. }
  608. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  609. return NO;
  610. }
  611. return YES;
  612. }
  613. + (NSString *)actualBundleID {
  614. return [[NSBundle mainBundle] bundleIdentifier];
  615. }
  616. /**
  617. * Validates that the format of the app ID string is what is expected based on the supplied version.
  618. * The version must end in ":".
  619. *
  620. * For v1 app ids the format is expected to be
  621. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  622. *
  623. * This method does not verify that the contents of the app id are correct, just that they fulfill
  624. * the expected format.
  625. *
  626. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  627. * @param version Indicates what version of the app id format this string should be.
  628. * @return YES if provided string fufills the expected format, NO otherwise.
  629. */
  630. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  631. if (!appID.length || !version.length) {
  632. return NO;
  633. }
  634. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  635. stringScanner.charactersToBeSkipped = nil;
  636. // Skip version part
  637. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  638. if (![stringScanner scanString:version intoString:NULL]) {
  639. // The version part is missing or mismatched
  640. return NO;
  641. }
  642. // Validate version part (see part between '*' symbols below)
  643. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  644. if (![stringScanner scanString:@":" intoString:NULL]) {
  645. // appIDVersion must be separated by ":"
  646. return NO;
  647. }
  648. // Validate version part (see part between '*' symbols below)
  649. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  650. NSInteger projectNumber = NSNotFound;
  651. if (![stringScanner scanInteger:&projectNumber]) {
  652. // NO project number found.
  653. return NO;
  654. }
  655. // Validate version part (see part between '*' symbols below)
  656. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  657. if (![stringScanner scanString:@":" intoString:NULL]) {
  658. // The project number must be separated by ":"
  659. return NO;
  660. }
  661. // Validate version part (see part between '*' symbols below)
  662. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  663. NSString *platform;
  664. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  665. return NO;
  666. }
  667. if (![platform isEqualToString:@"ios"]) {
  668. // The platform must be @"ios"
  669. return NO;
  670. }
  671. // Validate version part (see part between '*' symbols below)
  672. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  673. if (![stringScanner scanString:@":" intoString:NULL]) {
  674. // The platform must be separated by ":"
  675. return NO;
  676. }
  677. // Validate version part (see part between '*' symbols below)
  678. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  679. unsigned long long fingerprint = NSNotFound;
  680. if (![stringScanner scanHexLongLong:&fingerprint]) {
  681. // Fingerprint part is missing
  682. return NO;
  683. }
  684. if (!stringScanner.isAtEnd) {
  685. // There are not allowed characters in the fingerprint part
  686. return NO;
  687. }
  688. return YES;
  689. }
  690. /**
  691. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  692. * version.
  693. *
  694. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  695. *
  696. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  697. * @param version Indicates what version of the app id format this string should be.
  698. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  699. * otherwise.
  700. */
  701. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  702. // Extract the supplied fingerprint from the supplied app ID.
  703. // This assumes the app ID format is the same for all known versions below. If the app ID format
  704. // changes in future versions, the tokenizing of the app ID format will need to take into account
  705. // the version of the app ID.
  706. NSArray *components = [appID componentsSeparatedByString:@":"];
  707. if (components.count != 4) {
  708. return NO;
  709. }
  710. NSString *suppliedFingerprintString = components[3];
  711. if (!suppliedFingerprintString.length) {
  712. return NO;
  713. }
  714. uint64_t suppliedFingerprint;
  715. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  716. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  717. return NO;
  718. }
  719. if ([version isEqual:@"1"]) {
  720. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  721. return YES;
  722. }
  723. // Unknown version.
  724. return NO;
  725. }
  726. - (NSString *)expectedBundleID {
  727. return _options.bundleID;
  728. }
  729. // end App ID validation
  730. #pragma mark - Reading From Plist & User Defaults
  731. /**
  732. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  733. * readability.
  734. */
  735. - (void)clearDataCollectionSwitchFromUserDefaults {
  736. NSString *key =
  737. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  738. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  739. }
  740. /**
  741. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  742. * readability.
  743. */
  744. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  745. // Read the object in user defaults, and only return if it's an NSNumber.
  746. NSString *key =
  747. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  748. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  749. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  750. return collectionEnabledDefaultsObject;
  751. }
  752. return nil;
  753. }
  754. /**
  755. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  756. * only read once from the plist and return the cached value.
  757. */
  758. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  759. static NSNumber *collectionEnabledPlistObject;
  760. static dispatch_once_t onceToken;
  761. dispatch_once(&onceToken, ^{
  762. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  763. id plistValue = [[NSBundle mainBundle]
  764. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  765. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  766. collectionEnabledPlistObject = (NSNumber *)plistValue;
  767. }
  768. });
  769. return collectionEnabledPlistObject;
  770. }
  771. #pragma mark - App Life Cycle
  772. - (void)subscribeForAppDidBecomeActiveNotifications {
  773. #if TARGET_OS_IOS || TARGET_OS_TV
  774. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  775. #elif TARGET_OS_OSX
  776. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  777. #endif
  778. #if !TARGET_OS_WATCH
  779. [[NSNotificationCenter defaultCenter] addObserver:self
  780. selector:@selector(appDidBecomeActive:)
  781. name:notificationName
  782. object:nil];
  783. #endif
  784. }
  785. - (void)appDidBecomeActive:(NSNotification *)notification {
  786. [self logCoreTelemetryIfEnabled];
  787. }
  788. - (void)logCoreTelemetryIfEnabled {
  789. if ([self isDataCollectionDefaultEnabled]) {
  790. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:_options];
  791. }
  792. }
  793. @end