FIRApp.m 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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/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. * The URL to download plist files.
  81. */
  82. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  83. /**
  84. * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle
  85. * events from Core.
  86. */
  87. static NSMutableArray<Class<FIRLibrary>> *sRegisteredAsConfigurable;
  88. @interface FIRApp ()
  89. #ifdef DEBUG
  90. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  91. #endif // DEBUG
  92. @end
  93. @implementation FIRApp
  94. // This is necessary since our custom getter prevents `_options` from being created.
  95. @synthesize options = _options;
  96. static NSMutableDictionary *sAllApps;
  97. static FIRApp *sDefaultApp;
  98. static NSMutableDictionary *sLibraryVersions;
  99. static dispatch_once_t sFirebaseUserAgentOnceToken;
  100. + (void)configure {
  101. FIROptions *options = [FIROptions defaultOptions];
  102. if (!options) {
  103. [NSException raise:kFirebaseCoreErrorDomain
  104. format:@"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find "
  105. @"a valid GoogleService-Info.plist in your project. Please download one "
  106. @"from %@.",
  107. kPlistURL];
  108. }
  109. [FIRApp configureWithOptions:options];
  110. #if TARGET_OS_OSX || TARGET_OS_TV
  111. FIRLogNotice(kFIRLoggerCore, @"I-COR000028",
  112. @"tvOS and macOS SDK support is not part of the official Firebase product. "
  113. @"Instead they are community supported. Details at "
  114. @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md.");
  115. #endif
  116. }
  117. + (void)configureWithOptions:(FIROptions *)options {
  118. if (!options) {
  119. [NSException raise:kFirebaseCoreErrorDomain
  120. format:@"Options is nil. Please pass a valid options."];
  121. }
  122. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  123. }
  124. + (NSCharacterSet *)applicationNameAllowedCharacters {
  125. static NSCharacterSet *applicationNameAllowedCharacters;
  126. static dispatch_once_t onceToken;
  127. dispatch_once(&onceToken, ^{
  128. NSMutableCharacterSet *allowedNameCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  129. [allowedNameCharacters addCharactersInString:@"-_"];
  130. applicationNameAllowedCharacters = [allowedNameCharacters copy];
  131. });
  132. return applicationNameAllowedCharacters;
  133. }
  134. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  135. if (!name || !options) {
  136. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  137. }
  138. if (name.length == 0) {
  139. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  140. }
  141. if ([name isEqualToString:kFIRDefaultAppName]) {
  142. if (sDefaultApp) {
  143. // The default app already exists. Handle duplicate `configure` calls and return.
  144. [self appWasConfiguredTwice:sDefaultApp usingOptions:options];
  145. return;
  146. }
  147. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  148. } else {
  149. // Validate the app name and ensure it hasn't been configured already.
  150. NSCharacterSet *nameCharacters = [NSCharacterSet characterSetWithCharactersInString:name];
  151. if (![[self applicationNameAllowedCharacters] isSupersetOfSet:nameCharacters]) {
  152. [NSException raise:kFirebaseCoreErrorDomain
  153. format:@"App name can only contain alphanumeric, "
  154. @"hyphen (-), and underscore (_) characters"];
  155. }
  156. @synchronized(self) {
  157. if (sAllApps && sAllApps[name]) {
  158. // The app already exists. Handle a duplicate `configure` call and return.
  159. [self appWasConfiguredTwice:sAllApps[name] usingOptions:options];
  160. return;
  161. }
  162. }
  163. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  164. }
  165. @synchronized(self) {
  166. FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options];
  167. if (app.isDefaultApp) {
  168. sDefaultApp = app;
  169. }
  170. [FIRApp addAppToAppDictionary:app];
  171. // The FIRApp instance is ready to go, `sDefaultApp` is assigned, other SDKs are now ready to be
  172. // instantiated.
  173. [app.container instantiateEagerComponents];
  174. [FIRApp sendNotificationsToSDKs:app];
  175. }
  176. }
  177. /// Called when `configure` has been called multiple times for the same app. This can either throw
  178. /// an exception (most cases) or ignore the duplicate configuration in situations where it's allowed
  179. /// like an extension.
  180. + (void)appWasConfiguredTwice:(FIRApp *)app usingOptions:(FIROptions *)options {
  181. // Only extensions should potentially be able to call `configure` more than once.
  182. if (![GULAppEnvironmentUtil isAppExtension]) {
  183. // Throw an exception since this is now an invalid state.
  184. if (app.isDefaultApp) {
  185. [NSException raise:kFirebaseCoreErrorDomain
  186. format:@"Default app has already been configured."];
  187. } else {
  188. [NSException raise:kFirebaseCoreErrorDomain
  189. format:@"App named %@ has already been configured.", app.name];
  190. }
  191. }
  192. // In an extension, the entry point could be called multiple times. As long as the options are
  193. // identical we should allow multiple `configure` calls.
  194. if ([options isEqual:app.options]) {
  195. // Everything is identical but the extension's lifecycle triggered `configure` twice.
  196. // Ignore duplicate calls and return since everything should still be in a valid state.
  197. FIRLogDebug(kFIRLoggerCore, @"I-COR000035",
  198. @"Ignoring second `configure` call in an extension.");
  199. return;
  200. } else {
  201. [NSException raise:kFirebaseCoreErrorDomain
  202. format:@"App named %@ has already been configured.", app.name];
  203. }
  204. }
  205. + (FIRApp *)defaultApp {
  206. if (sDefaultApp) {
  207. return sDefaultApp;
  208. }
  209. FIRLogError(kFIRLoggerCore, @"I-COR000003",
  210. @"The default Firebase app has not yet been "
  211. @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your "
  212. @"application initialization. Read more: https://goo.gl/ctyzm8.");
  213. return nil;
  214. }
  215. + (FIRApp *)appNamed:(NSString *)name {
  216. @synchronized(self) {
  217. if (sAllApps) {
  218. FIRApp *app = sAllApps[name];
  219. if (app) {
  220. return app;
  221. }
  222. }
  223. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  224. return nil;
  225. }
  226. }
  227. + (NSDictionary *)allApps {
  228. @synchronized(self) {
  229. if (!sAllApps) {
  230. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  231. }
  232. return [sAllApps copy];
  233. }
  234. }
  235. // Public only for tests
  236. + (void)resetApps {
  237. @synchronized(self) {
  238. sDefaultApp = nil;
  239. [sAllApps removeAllObjects];
  240. sAllApps = nil;
  241. [sLibraryVersions removeAllObjects];
  242. sLibraryVersions = nil;
  243. sFirebaseUserAgentOnceToken = 0;
  244. }
  245. }
  246. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  247. @synchronized([self class]) {
  248. if (sAllApps && sAllApps[self.name]) {
  249. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  250. // Remove all registered libraries from the container to avoid creating new instances.
  251. [self.container removeAllComponents];
  252. // Remove all cached instances from the container before deleting the app.
  253. [self.container removeAllCachedInstances];
  254. [sAllApps removeObjectForKey:self.name];
  255. [self clearDataCollectionSwitchFromUserDefaults];
  256. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  257. sDefaultApp = nil;
  258. }
  259. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  260. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  261. object:[self class]
  262. userInfo:appInfoDict];
  263. completion(YES);
  264. } else {
  265. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  266. completion(NO);
  267. }
  268. }
  269. }
  270. + (void)addAppToAppDictionary:(FIRApp *)app {
  271. if (!sAllApps) {
  272. sAllApps = [NSMutableDictionary dictionary];
  273. }
  274. if ([app configureCore]) {
  275. sAllApps[app.name] = app;
  276. } else {
  277. [NSException raise:kFirebaseCoreErrorDomain
  278. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  279. @"GoogleService-Info.plist or set in the customized options."];
  280. }
  281. }
  282. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  283. self = [super init];
  284. if (self) {
  285. _name = [name copy];
  286. _options = [options copy];
  287. _options.editingLocked = YES;
  288. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  289. _container = [[FIRComponentContainer alloc] initWithApp:self];
  290. }
  291. return self;
  292. }
  293. - (void)dealloc {
  294. [[NSNotificationCenter defaultCenter] removeObserver:self];
  295. }
  296. - (BOOL)configureCore {
  297. [self checkExpectedBundleID];
  298. if (![self isAppIDValid]) {
  299. return NO;
  300. }
  301. [self logCoreTelemetryIfEnabled];
  302. #if TARGET_OS_IOS
  303. // Initialize the Analytics once there is a valid options under default app. Analytics should
  304. // always initialize first by itself before the other SDKs.
  305. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  306. Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics");
  307. if (firAnalyticsClass) {
  308. #pragma clang diagnostic push
  309. #pragma clang diagnostic ignored "-Wundeclared-selector"
  310. SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:);
  311. #pragma clang diagnostic pop
  312. if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) {
  313. #pragma clang diagnostic push
  314. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  315. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  316. [firAnalyticsClass performSelector:startWithConfigurationSelector
  317. withObject:[FIRConfiguration sharedInstance].analyticsConfiguration
  318. withObject:_options];
  319. #pragma clang diagnostic pop
  320. }
  321. }
  322. }
  323. #endif
  324. [self subscribeForAppDidBecomeActiveNotifications];
  325. return YES;
  326. }
  327. - (FIROptions *)options {
  328. return [_options copy];
  329. }
  330. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  331. #ifdef DEBUG
  332. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  333. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  334. self.alreadyOutputDataCollectionFlag = YES;
  335. #endif // DEBUG
  336. NSString *key =
  337. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  338. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  339. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  340. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  341. // default app, so return if this isn't the default app.
  342. if (!self.isDefaultApp) {
  343. return;
  344. }
  345. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  346. if ([self.options isAnalyticsCollectionExplicitlySet]) {
  347. return;
  348. }
  349. // The Analytics flag has not been explicitly set, so update with the value being set.
  350. #pragma clang diagnostic push
  351. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  352. [[FIRAnalyticsConfiguration sharedInstance]
  353. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  354. persistSetting:NO];
  355. #pragma clang diagnostic pop
  356. }
  357. - (BOOL)isDataCollectionDefaultEnabled {
  358. return [self isGlobalDataCollectionEnabled];
  359. }
  360. /// Returns a BOOL indicating if data collection is enabled based on various Info.plist and runtime
  361. /// flags. Each product can override this themselves with their own product specific flags, but if
  362. /// no product specific flags are used this is the default.
  363. - (BOOL)isGlobalDataCollectionEnabled {
  364. // Check if it's been manually set before in code, and use that as the higher priority value.
  365. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  366. if (defaultsObject != nil) {
  367. #ifdef DEBUG
  368. if (!self.alreadyOutputDataCollectionFlag) {
  369. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  370. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  371. self.alreadyOutputDataCollectionFlag = YES;
  372. }
  373. #endif // DEBUG
  374. return [defaultsObject boolValue];
  375. }
  376. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  377. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  378. // no performance impact calling multiple times.
  379. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  380. if (collectionEnabledPlistValue != nil) {
  381. #ifdef DEBUG
  382. if (!self.alreadyOutputDataCollectionFlag) {
  383. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  384. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  385. self.alreadyOutputDataCollectionFlag = YES;
  386. }
  387. #endif // DEBUG
  388. return [collectionEnabledPlistValue boolValue];
  389. }
  390. #ifdef DEBUG
  391. if (!self.alreadyOutputDataCollectionFlag) {
  392. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  393. self.alreadyOutputDataCollectionFlag = YES;
  394. }
  395. #endif // DEBUG
  396. return YES;
  397. }
  398. - (void)setDataCollectionDefaultState:(FIRDataCollectionState)state {
  399. #ifdef DEBUG
  400. NSString *textValue;
  401. switch (state) {
  402. case FIRDataCollectionStateDefault:
  403. textValue = @"Default";
  404. break;
  405. case FIRDataCollectionStateEnabled:
  406. textValue = @"Enabled";
  407. break;
  408. case FIRDataCollectionStateDisabled:
  409. textValue = @"Disabled";
  410. break;
  411. }
  412. FIRLogDebug(kFIRLoggerCore, @"I-COR000036", @"Explicitly set collection flag to: %@.", textValue);
  413. self.alreadyOutputDataCollectionFlag = YES;
  414. #endif // DEBUG
  415. NSString *key =
  416. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  417. switch (state) {
  418. case FIRDataCollectionStateDefault:
  419. // Remove the runtime flag, defaults to whatever is set by the Info.plist otherwise defaults
  420. // to enabled.
  421. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  422. break;
  423. case FIRDataCollectionStateEnabled:
  424. [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
  425. break;
  426. case FIRDataCollectionStateDisabled:
  427. [[NSUserDefaults standardUserDefaults] setBool:NO forKey:key];
  428. break;
  429. }
  430. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  431. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  432. // default app, so return if this isn't the default app.
  433. if (!self.isDefaultApp) {
  434. return;
  435. }
  436. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  437. if ([self.options isAnalyticsCollectionExplicitlySet]) {
  438. return;
  439. }
  440. // The Analytics flag has not been explicitly set, so update with the value being set.
  441. #pragma clang diagnostic push
  442. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  443. [[FIRAnalyticsConfiguration sharedInstance]
  444. setAnalyticsCollectionEnabled:[self isGlobalDataCollectionEnabled]
  445. persistSetting:NO];
  446. #pragma clang diagnostic pop
  447. }
  448. - (FIRDataCollectionState)dataCollectionDefaultState {
  449. // The mechanism used to be a BOOL value, use that underlying storage to determine what the state
  450. // is.
  451. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  452. if (defaultsObject == nil) {
  453. // No value was saved, it's the default state.
  454. return FIRDataCollectionStateDefault;
  455. }
  456. // There's a value stored, check what it is and compare it to the enum values.
  457. BOOL isCollectionEnabled = [defaultsObject boolValue];
  458. if (isCollectionEnabled) {
  459. return FIRDataCollectionStateEnabled;
  460. } else {
  461. return FIRDataCollectionStateDisabled;
  462. }
  463. }
  464. #pragma mark - private
  465. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  466. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  467. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  468. NSDictionary *appInfoDict = @{
  469. kFIRAppNameKey : app.name,
  470. kFIRAppIsDefaultAppKey : isDefaultApp,
  471. kFIRGoogleAppIDKey : app.options.googleAppID
  472. };
  473. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  474. object:self
  475. userInfo:appInfoDict];
  476. // This is the new way of sending information to SDKs.
  477. // TODO: Do we want this on a background thread, maybe?
  478. @synchronized(self) {
  479. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  480. [library configureWithApp:app];
  481. }
  482. }
  483. }
  484. + (NSError *)errorForMissingOptions {
  485. NSDictionary *errorDict = @{
  486. NSLocalizedDescriptionKey :
  487. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  488. NSLocalizedRecoverySuggestionErrorKey :
  489. @"Check formatting and location of GoogleService-Info.plist."
  490. };
  491. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  492. code:FIRErrorCodeInvalidPlistFile
  493. userInfo:errorDict];
  494. }
  495. + (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain
  496. errorCode:(FIRErrorCode)code
  497. service:(NSString *)service
  498. reason:(NSString *)reason {
  499. NSString *description =
  500. [NSString stringWithFormat:@"Configuration failed for service %@.", service];
  501. NSDictionary *errorDict =
  502. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  503. return [NSError errorWithDomain:domain code:code userInfo:errorDict];
  504. }
  505. + (NSError *)errorForInvalidAppID {
  506. NSDictionary *errorDict = @{
  507. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  508. NSLocalizedRecoverySuggestionErrorKey :
  509. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  510. @"customized options."
  511. };
  512. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  513. code:FIRErrorCodeInvalidAppID
  514. userInfo:errorDict];
  515. }
  516. + (BOOL)isDefaultAppConfigured {
  517. return (sDefaultApp != nil);
  518. }
  519. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  520. // Create the set of characters which aren't allowed, only if this feature is used.
  521. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  522. [allowedSet addCharactersInString:@"-_."];
  523. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  524. // Make sure the library name and version strings do not contain unexpected characters, and
  525. // add the name/version pair to the dictionary.
  526. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  527. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  528. @synchronized(self) {
  529. if (!sLibraryVersions) {
  530. sLibraryVersions = [[NSMutableDictionary alloc] init];
  531. }
  532. sLibraryVersions[name] = version;
  533. }
  534. } else {
  535. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  536. @"The library name (%@) or version number (%@) contain invalid characters. "
  537. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  538. name, version);
  539. }
  540. }
  541. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  542. withName:(nonnull NSString *)name
  543. withVersion:(nonnull NSString *)version {
  544. // This is called at +load time, keep the work to a minimum.
  545. // Ensure the class given conforms to the proper protocol.
  546. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  547. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  548. [NSException raise:NSInvalidArgumentException
  549. format:@"Class %@ attempted to register components, but it does not conform to "
  550. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  551. library];
  552. }
  553. [FIRComponentContainer registerAsComponentRegistrant:library];
  554. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  555. static dispatch_once_t onceToken;
  556. dispatch_once(&onceToken, ^{
  557. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  558. });
  559. @synchronized(self) {
  560. [sRegisteredAsConfigurable addObject:library];
  561. }
  562. }
  563. [self registerLibrary:name withVersion:version];
  564. }
  565. + (NSString *)firebaseUserAgent {
  566. @synchronized(self) {
  567. dispatch_once(&sFirebaseUserAgentOnceToken, ^{
  568. // Report FirebaseCore version for useragent string
  569. [FIRApp registerLibrary:@"fire-ios"
  570. withVersion:[NSString stringWithUTF8String:FIRCoreVersionString]];
  571. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  572. NSString *xcodeVersion = info[@"DTXcodeBuild"];
  573. NSString *sdkVersion = info[@"DTSDKBuild"];
  574. if (xcodeVersion) {
  575. [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion];
  576. }
  577. if (sdkVersion) {
  578. [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion];
  579. }
  580. NSString *swiftFlagValue = [self hasSwiftRuntime] ? @"true" : @"false";
  581. [FIRApp registerLibrary:@"swift" withVersion:swiftFlagValue];
  582. [FIRApp registerLibrary:kFIRAppDiagnosticsApplePlatformPrefix
  583. withVersion:[self applePlatform]];
  584. });
  585. NSMutableArray<NSString *> *libraries =
  586. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  587. for (NSString *libraryName in sLibraryVersions) {
  588. [libraries addObject:[NSString stringWithFormat:@"%@/%@", libraryName,
  589. sLibraryVersions[libraryName]]];
  590. }
  591. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  592. return [libraries componentsJoinedByString:@" "];
  593. }
  594. }
  595. + (BOOL)hasSwiftRuntime {
  596. // The class
  597. // [Swift._SwiftObject](https://github.com/apple/swift/blob/5eac3e2818eb340b11232aff83edfbd1c307fa03/stdlib/public/runtime/SwiftObject.h#L35)
  598. // is a part of Swift runtime, so it should be present if Swift runtime is available.
  599. BOOL hasSwiftRuntime =
  600. objc_lookUpClass("Swift._SwiftObject") != nil ||
  601. // Swift object class name before
  602. // https://github.com/apple/swift/commit/9637b4a6e11ddca72f5f6dbe528efc7c92f14d01
  603. objc_getClass("_TtCs12_SwiftObject") != nil;
  604. return hasSwiftRuntime;
  605. }
  606. + (NSString *)applePlatform {
  607. NSString *applePlatform = @"unknown";
  608. // When a Catalyst app is run on macOS then both `TARGET_OS_MACCATALYST` and `TARGET_OS_IOS` are
  609. // `true`, which means the condition list is order-sensitive.
  610. #if TARGET_OS_MACCATALYST
  611. applePlatform = @"maccatalyst";
  612. #elif TARGET_OS_IOS
  613. applePlatform = @"ios";
  614. #elif TARGET_OS_TV
  615. applePlatform = @"tvos";
  616. #elif TARGET_OS_OSX
  617. applePlatform = @"macos";
  618. #elif TARGET_OS_WATCH
  619. applePlatform = @"watchos";
  620. #endif
  621. return applePlatform;
  622. }
  623. - (void)checkExpectedBundleID {
  624. NSArray *bundles = [FIRBundleUtil relevantBundles];
  625. NSString *expectedBundleID = [self expectedBundleID];
  626. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  627. // backward compatibility.
  628. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  629. inBundles:bundles]) {
  630. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  631. @"The project's Bundle ID is inconsistent with "
  632. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  633. @"using a customized options. To ensure that everything can be configured "
  634. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  635. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  636. @"download a new configuration file that matches your bundle identifier from %@ "
  637. @"and replace the current one.",
  638. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  639. }
  640. }
  641. #pragma mark - private - App ID Validation
  642. /**
  643. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  644. * This is the main method for validating app ID.
  645. *
  646. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  647. */
  648. - (BOOL)isAppIDValid {
  649. NSString *appID = _options.googleAppID;
  650. BOOL isValid = [FIRApp validateAppID:appID];
  651. if (!isValid) {
  652. NSString *expectedBundleID = [self expectedBundleID];
  653. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  654. @"The GOOGLE_APP_ID either in the plist file "
  655. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  656. @"the plist file, use the iOS version of bundle identifier to download the file, "
  657. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  658. @"identifier to '%@'. Or you can download a new configuration file that matches "
  659. @"your bundle identifier from %@ and replace the current one.",
  660. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  661. };
  662. return isValid;
  663. }
  664. + (BOOL)validateAppID:(NSString *)appID {
  665. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  666. // have a valid fingerprint, otherwise we just warn about the potential issue.
  667. if (!appID.length) {
  668. return NO;
  669. }
  670. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  671. stringScanner.charactersToBeSkipped = nil;
  672. NSString *appIDVersion;
  673. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  674. intoString:&appIDVersion]) {
  675. return NO;
  676. }
  677. if (![stringScanner scanString:@":" intoString:NULL]) {
  678. // appIDVersion must be separated by ":"
  679. return NO;
  680. }
  681. NSArray *knownVersions = @[ @"1" ];
  682. if (![knownVersions containsObject:appIDVersion]) {
  683. // Permit unknown yet properly formatted app ID versions.
  684. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  685. return YES;
  686. }
  687. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  688. return NO;
  689. }
  690. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  691. return NO;
  692. }
  693. return YES;
  694. }
  695. + (NSString *)actualBundleID {
  696. return [[NSBundle mainBundle] bundleIdentifier];
  697. }
  698. /**
  699. * Validates that the format of the app ID string is what is expected based on the supplied version.
  700. * The version must end in ":".
  701. *
  702. * For v1 app ids the format is expected to be
  703. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  704. *
  705. * This method does not verify that the contents of the app id are correct, just that they fulfill
  706. * the expected format.
  707. *
  708. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  709. * @param version Indicates what version of the app id format this string should be.
  710. * @return YES if provided string fufills the expected format, NO otherwise.
  711. */
  712. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  713. if (!appID.length || !version.length) {
  714. return NO;
  715. }
  716. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  717. stringScanner.charactersToBeSkipped = nil;
  718. // Skip version part
  719. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  720. if (![stringScanner scanString:version intoString:NULL]) {
  721. // The version part is missing or mismatched
  722. return NO;
  723. }
  724. // Validate version part (see part between '*' symbols below)
  725. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  726. if (![stringScanner scanString:@":" intoString:NULL]) {
  727. // appIDVersion must be separated by ":"
  728. return NO;
  729. }
  730. // Validate version part (see part between '*' symbols below)
  731. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  732. NSInteger projectNumber = NSNotFound;
  733. if (![stringScanner scanInteger:&projectNumber]) {
  734. // NO project number found.
  735. return NO;
  736. }
  737. // Validate version part (see part between '*' symbols below)
  738. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  739. if (![stringScanner scanString:@":" intoString:NULL]) {
  740. // The project number must be separated by ":"
  741. return NO;
  742. }
  743. // Validate version part (see part between '*' symbols below)
  744. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  745. NSString *platform;
  746. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  747. return NO;
  748. }
  749. if (![platform isEqualToString:@"ios"]) {
  750. // The platform must be @"ios"
  751. return NO;
  752. }
  753. // Validate version part (see part between '*' symbols below)
  754. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  755. if (![stringScanner scanString:@":" intoString:NULL]) {
  756. // The platform must be separated by ":"
  757. return NO;
  758. }
  759. // Validate version part (see part between '*' symbols below)
  760. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  761. unsigned long long fingerprint = NSNotFound;
  762. if (![stringScanner scanHexLongLong:&fingerprint]) {
  763. // Fingerprint part is missing
  764. return NO;
  765. }
  766. if (!stringScanner.isAtEnd) {
  767. // There are not allowed characters in the fingerprint part
  768. return NO;
  769. }
  770. return YES;
  771. }
  772. /**
  773. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  774. * version.
  775. *
  776. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  777. *
  778. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  779. * @param version Indicates what version of the app id format this string should be.
  780. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  781. * otherwise.
  782. */
  783. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  784. // Extract the supplied fingerprint from the supplied app ID.
  785. // This assumes the app ID format is the same for all known versions below. If the app ID format
  786. // changes in future versions, the tokenizing of the app ID format will need to take into account
  787. // the version of the app ID.
  788. NSArray *components = [appID componentsSeparatedByString:@":"];
  789. if (components.count != 4) {
  790. return NO;
  791. }
  792. NSString *suppliedFingerprintString = components[3];
  793. if (!suppliedFingerprintString.length) {
  794. return NO;
  795. }
  796. uint64_t suppliedFingerprint;
  797. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  798. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  799. return NO;
  800. }
  801. if ([version isEqual:@"1"]) {
  802. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  803. return YES;
  804. }
  805. // Unknown version.
  806. return NO;
  807. }
  808. - (NSString *)expectedBundleID {
  809. return _options.bundleID;
  810. }
  811. // end App ID validation
  812. #pragma mark - Reading From Plist & User Defaults
  813. /**
  814. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  815. * readability.
  816. */
  817. - (void)clearDataCollectionSwitchFromUserDefaults {
  818. NSString *key =
  819. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  820. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  821. }
  822. /**
  823. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  824. * readability.
  825. */
  826. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  827. // Read the object in user defaults, and only return if it's an NSNumber.
  828. NSString *key =
  829. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  830. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  831. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  832. return collectionEnabledDefaultsObject;
  833. }
  834. return nil;
  835. }
  836. /**
  837. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  838. * only read once from the plist and return the cached value.
  839. */
  840. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  841. static NSNumber *collectionEnabledPlistObject;
  842. static dispatch_once_t onceToken;
  843. dispatch_once(&onceToken, ^{
  844. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  845. id plistValue = [[NSBundle mainBundle]
  846. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  847. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  848. collectionEnabledPlistObject = (NSNumber *)plistValue;
  849. }
  850. });
  851. return collectionEnabledPlistObject;
  852. }
  853. #pragma mark - Sending Logs
  854. #pragma clang diagnostic push
  855. #pragma clang diagnostic ignored "-Wunused-parameter"
  856. - (void)sendLogsWithServiceName:(NSString *)serviceName
  857. version:(NSString *)version
  858. error:(NSError *)error {
  859. // Do nothing. Please remove calls to this method.
  860. }
  861. #pragma clang diagnostic pop
  862. #pragma mark - App Life Cycle
  863. - (void)subscribeForAppDidBecomeActiveNotifications {
  864. #if TARGET_OS_IOS || TARGET_OS_TV
  865. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  866. #elif TARGET_OS_OSX
  867. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  868. #endif
  869. #if !TARGET_OS_WATCH
  870. [[NSNotificationCenter defaultCenter] addObserver:self
  871. selector:@selector(appDidBecomeActive:)
  872. name:notificationName
  873. object:nil];
  874. #endif
  875. }
  876. - (void)appDidBecomeActive:(NSNotification *)notification {
  877. [self logCoreTelemetryIfEnabled];
  878. }
  879. - (void)logCoreTelemetryIfEnabled {
  880. if ([self isGlobalDataCollectionEnabled]) {
  881. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:_options];
  882. }
  883. }
  884. @end