FIRApp.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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/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 "FirebaseCore/Sources/Public/FirebaseCore/FIRVersion.h"
  33. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  34. #import <objc/runtime.h>
  35. // The kFIRService strings are only here while transitioning CoreDiagnostics from the Analytics
  36. // pod to a Core dependency. These symbols are not used and should be deleted after the transition.
  37. NSString *const kFIRServiceAdMob;
  38. NSString *const kFIRServiceAuth;
  39. NSString *const kFIRServiceAuthUI;
  40. NSString *const kFIRServiceCrash;
  41. NSString *const kFIRServiceDatabase;
  42. NSString *const kFIRServiceDynamicLinks;
  43. NSString *const kFIRServiceFirestore;
  44. NSString *const kFIRServiceFunctions;
  45. NSString *const kFIRServiceInstanceID;
  46. NSString *const kFIRServiceInvites;
  47. NSString *const kFIRServiceMessaging;
  48. NSString *const kFIRServiceMeasurement;
  49. NSString *const kFIRServicePerformance;
  50. NSString *const kFIRServiceRemoteConfig;
  51. NSString *const kFIRServiceStorage;
  52. NSString *const kGGLServiceAnalytics;
  53. NSString *const kGGLServiceSignIn;
  54. NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT";
  55. NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification";
  56. NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification";
  57. NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey";
  58. NSString *const kFIRAppNameKey = @"FIRAppNameKey";
  59. NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey";
  60. NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat =
  61. @"/google/firebase/global_data_collection_enabled:%@";
  62. NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey =
  63. @"FirebaseDataCollectionDefaultEnabled";
  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. /** The NSUserDefaults suite name for FirebaseCore, for those storage locations that use it. */
  84. NSString *const kFirebaseCoreDefaultsSuiteName = @"com.firebase.core";
  85. /**
  86. * The URL to download plist files.
  87. */
  88. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  89. /**
  90. * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle
  91. * events from Core.
  92. */
  93. static NSMutableArray<Class<FIRLibrary>> *sRegisteredAsConfigurable;
  94. @interface FIRApp ()
  95. #ifdef DEBUG
  96. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  97. #endif // DEBUG
  98. @end
  99. @implementation FIRApp
  100. // This is necessary since our custom getter prevents `_options` from being created.
  101. @synthesize options = _options;
  102. static NSMutableDictionary *sAllApps;
  103. static FIRApp *sDefaultApp;
  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. [[self userAgent] reset];
  246. }
  247. }
  248. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  249. @synchronized([self class]) {
  250. if (sAllApps && sAllApps[self.name]) {
  251. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  252. // Remove all registered libraries from the container to avoid creating new instances.
  253. [self.container removeAllComponents];
  254. // Remove all cached instances from the container before deleting the app.
  255. [self.container removeAllCachedInstances];
  256. [sAllApps removeObjectForKey:self.name];
  257. [self clearDataCollectionSwitchFromUserDefaults];
  258. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  259. sDefaultApp = nil;
  260. }
  261. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  262. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  263. object:[self class]
  264. userInfo:appInfoDict];
  265. completion(YES);
  266. } else {
  267. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  268. completion(NO);
  269. }
  270. }
  271. }
  272. + (void)addAppToAppDictionary:(FIRApp *)app {
  273. if (!sAllApps) {
  274. sAllApps = [NSMutableDictionary dictionary];
  275. }
  276. if ([app configureCore]) {
  277. sAllApps[app.name] = app;
  278. } else {
  279. [NSException raise:kFirebaseCoreErrorDomain
  280. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  281. @"GoogleService-Info.plist or set in the customized options."];
  282. }
  283. }
  284. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  285. self = [super init];
  286. if (self) {
  287. _name = [name copy];
  288. _options = [options copy];
  289. _options.editingLocked = YES;
  290. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  291. _container = [[FIRComponentContainer alloc] initWithApp:self];
  292. }
  293. return self;
  294. }
  295. - (void)dealloc {
  296. [[NSNotificationCenter defaultCenter] removeObserver:self];
  297. }
  298. - (BOOL)configureCore {
  299. [self checkExpectedBundleID];
  300. if (![self isAppIDValid]) {
  301. return NO;
  302. }
  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. [self subscribeForAppDidBecomeActiveNotifications];
  324. return YES;
  325. }
  326. - (FIROptions *)options {
  327. return [_options copy];
  328. }
  329. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  330. #ifdef DEBUG
  331. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  332. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  333. self.alreadyOutputDataCollectionFlag = YES;
  334. #endif // DEBUG
  335. NSString *key =
  336. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  337. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  338. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  339. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  340. // default app, so return if this isn't the default app.
  341. if (!self.isDefaultApp) {
  342. return;
  343. }
  344. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  345. if ([self.options isAnalyticsCollectionExplicitlySet]) {
  346. return;
  347. }
  348. // The Analytics flag has not been explicitly set, so update with the value being set.
  349. #pragma clang diagnostic push
  350. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  351. [[FIRAnalyticsConfiguration sharedInstance]
  352. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  353. persistSetting:NO];
  354. #pragma clang diagnostic pop
  355. }
  356. - (BOOL)isDataCollectionDefaultEnabled {
  357. // Check if it's been manually set before in code, and use that as the higher priority value.
  358. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  359. if (defaultsObject != nil) {
  360. #ifdef DEBUG
  361. if (!self.alreadyOutputDataCollectionFlag) {
  362. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  363. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  364. self.alreadyOutputDataCollectionFlag = YES;
  365. }
  366. #endif // DEBUG
  367. return [defaultsObject boolValue];
  368. }
  369. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  370. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  371. // no performance impact calling multiple times.
  372. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  373. if (collectionEnabledPlistValue != nil) {
  374. #ifdef DEBUG
  375. if (!self.alreadyOutputDataCollectionFlag) {
  376. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  377. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  378. self.alreadyOutputDataCollectionFlag = YES;
  379. }
  380. #endif // DEBUG
  381. return [collectionEnabledPlistValue boolValue];
  382. }
  383. #ifdef DEBUG
  384. if (!self.alreadyOutputDataCollectionFlag) {
  385. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  386. self.alreadyOutputDataCollectionFlag = YES;
  387. }
  388. #endif // DEBUG
  389. return YES;
  390. }
  391. #pragma mark - private
  392. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  393. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  394. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  395. NSDictionary *appInfoDict = @{
  396. kFIRAppNameKey : app.name,
  397. kFIRAppIsDefaultAppKey : isDefaultApp,
  398. kFIRGoogleAppIDKey : app.options.googleAppID
  399. };
  400. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  401. object:self
  402. userInfo:appInfoDict];
  403. // This is the new way of sending information to SDKs.
  404. // TODO: Do we want this on a background thread, maybe?
  405. @synchronized(self) {
  406. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  407. [library configureWithApp:app];
  408. }
  409. }
  410. }
  411. + (NSError *)errorForMissingOptions {
  412. NSDictionary *errorDict = @{
  413. NSLocalizedDescriptionKey :
  414. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  415. NSLocalizedRecoverySuggestionErrorKey :
  416. @"Check formatting and location of GoogleService-Info.plist."
  417. };
  418. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-100 userInfo:errorDict];
  419. }
  420. + (NSError *)errorForInvalidAppID {
  421. NSDictionary *errorDict = @{
  422. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  423. NSLocalizedRecoverySuggestionErrorKey :
  424. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  425. @"customized options."
  426. };
  427. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-101 userInfo:errorDict];
  428. }
  429. + (BOOL)isDefaultAppConfigured {
  430. return (sDefaultApp != nil);
  431. }
  432. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  433. // Create the set of characters which aren't allowed, only if this feature is used.
  434. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  435. [allowedSet addCharactersInString:@"-_."];
  436. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  437. // Make sure the library name and version strings do not contain unexpected characters, and
  438. // add the name/version pair to the dictionary.
  439. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  440. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  441. [[self userAgent] setValue:version forComponent:name];
  442. } else {
  443. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  444. @"The library name (%@) or version number (%@) contain invalid characters. "
  445. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  446. name, version);
  447. }
  448. }
  449. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  450. withName:(nonnull NSString *)name {
  451. [self registerInternalLibrary:library withName:name withVersion:FIRFirebaseVersion()];
  452. }
  453. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  454. withName:(nonnull NSString *)name
  455. withVersion:(nonnull NSString *)version {
  456. // This is called at +load time, keep the work to a minimum.
  457. // Ensure the class given conforms to the proper protocol.
  458. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  459. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  460. [NSException raise:NSInvalidArgumentException
  461. format:@"Class %@ attempted to register components, but it does not conform to "
  462. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  463. library];
  464. }
  465. [FIRComponentContainer registerAsComponentRegistrant:library];
  466. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  467. static dispatch_once_t onceToken;
  468. dispatch_once(&onceToken, ^{
  469. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  470. });
  471. @synchronized(self) {
  472. [sRegisteredAsConfigurable addObject:library];
  473. }
  474. }
  475. [self registerLibrary:name withVersion:version];
  476. }
  477. + (FIRFirebaseUserAgent *)userAgent {
  478. static dispatch_once_t onceToken;
  479. static FIRFirebaseUserAgent *_userAgent;
  480. dispatch_once(&onceToken, ^{
  481. _userAgent = [[FIRFirebaseUserAgent alloc] init];
  482. [_userAgent setValue:FIRFirebaseVersion() forComponent:@"fire-ios"];
  483. });
  484. return _userAgent;
  485. }
  486. + (NSString *)firebaseUserAgent {
  487. return [[self userAgent] firebaseUserAgent];
  488. }
  489. - (void)checkExpectedBundleID {
  490. NSArray *bundles = [FIRBundleUtil relevantBundles];
  491. NSString *expectedBundleID = [self expectedBundleID];
  492. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  493. // backward compatibility.
  494. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  495. inBundles:bundles]) {
  496. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  497. @"The project's Bundle ID is inconsistent with "
  498. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  499. @"using a customized options. To ensure that everything can be configured "
  500. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  501. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  502. @"download a new configuration file that matches your bundle identifier from %@ "
  503. @"and replace the current one.",
  504. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  505. }
  506. }
  507. #pragma mark - private - App ID Validation
  508. /**
  509. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  510. * This is the main method for validating app ID.
  511. *
  512. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  513. */
  514. - (BOOL)isAppIDValid {
  515. NSString *appID = _options.googleAppID;
  516. BOOL isValid = [FIRApp validateAppID:appID];
  517. if (!isValid) {
  518. NSString *expectedBundleID = [self expectedBundleID];
  519. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  520. @"The GOOGLE_APP_ID either in the plist file "
  521. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  522. @"the plist file, use the iOS version of bundle identifier to download the file, "
  523. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  524. @"identifier to '%@'. Or you can download a new configuration file that matches "
  525. @"your bundle identifier from %@ and replace the current one.",
  526. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  527. };
  528. return isValid;
  529. }
  530. + (BOOL)validateAppID:(NSString *)appID {
  531. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  532. // have a valid fingerprint, otherwise we just warn about the potential issue.
  533. if (!appID.length) {
  534. return NO;
  535. }
  536. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  537. stringScanner.charactersToBeSkipped = nil;
  538. NSString *appIDVersion;
  539. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  540. intoString:&appIDVersion]) {
  541. return NO;
  542. }
  543. if (![stringScanner scanString:@":" intoString:NULL]) {
  544. // appIDVersion must be separated by ":"
  545. return NO;
  546. }
  547. NSArray *knownVersions = @[ @"1" ];
  548. if (![knownVersions containsObject:appIDVersion]) {
  549. // Permit unknown yet properly formatted app ID versions.
  550. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  551. return YES;
  552. }
  553. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  554. return NO;
  555. }
  556. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  557. return NO;
  558. }
  559. return YES;
  560. }
  561. + (NSString *)actualBundleID {
  562. return [[NSBundle mainBundle] bundleIdentifier];
  563. }
  564. /**
  565. * Validates that the format of the app ID string is what is expected based on the supplied version.
  566. * The version must end in ":".
  567. *
  568. * For v1 app ids the format is expected to be
  569. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  570. *
  571. * This method does not verify that the contents of the app id are correct, just that they fulfill
  572. * the expected format.
  573. *
  574. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  575. * @param version Indicates what version of the app id format this string should be.
  576. * @return YES if provided string fufills the expected format, NO otherwise.
  577. */
  578. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  579. if (!appID.length || !version.length) {
  580. return NO;
  581. }
  582. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  583. stringScanner.charactersToBeSkipped = nil;
  584. // Skip version part
  585. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  586. if (![stringScanner scanString:version intoString:NULL]) {
  587. // The version part is missing or mismatched
  588. return NO;
  589. }
  590. // Validate version part (see part between '*' symbols below)
  591. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  592. if (![stringScanner scanString:@":" intoString:NULL]) {
  593. // appIDVersion must be separated by ":"
  594. return NO;
  595. }
  596. // Validate version part (see part between '*' symbols below)
  597. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  598. NSInteger projectNumber = NSNotFound;
  599. if (![stringScanner scanInteger:&projectNumber]) {
  600. // NO project number found.
  601. return NO;
  602. }
  603. // Validate version part (see part between '*' symbols below)
  604. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  605. if (![stringScanner scanString:@":" intoString:NULL]) {
  606. // The project number must be separated by ":"
  607. return NO;
  608. }
  609. // Validate version part (see part between '*' symbols below)
  610. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  611. NSString *platform;
  612. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  613. return NO;
  614. }
  615. if (![platform isEqualToString:@"ios"]) {
  616. // The platform must be @"ios"
  617. return NO;
  618. }
  619. // Validate version part (see part between '*' symbols below)
  620. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  621. if (![stringScanner scanString:@":" intoString:NULL]) {
  622. // The platform must be separated by ":"
  623. return NO;
  624. }
  625. // Validate version part (see part between '*' symbols below)
  626. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  627. unsigned long long fingerprint = NSNotFound;
  628. if (![stringScanner scanHexLongLong:&fingerprint]) {
  629. // Fingerprint part is missing
  630. return NO;
  631. }
  632. if (!stringScanner.isAtEnd) {
  633. // There are not allowed characters in the fingerprint part
  634. return NO;
  635. }
  636. return YES;
  637. }
  638. /**
  639. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  640. * version.
  641. *
  642. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  643. *
  644. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  645. * @param version Indicates what version of the app id format this string should be.
  646. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  647. * otherwise.
  648. */
  649. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  650. // Extract the supplied fingerprint from the supplied app ID.
  651. // This assumes the app ID format is the same for all known versions below. If the app ID format
  652. // changes in future versions, the tokenizing of the app ID format will need to take into account
  653. // the version of the app ID.
  654. NSArray *components = [appID componentsSeparatedByString:@":"];
  655. if (components.count != 4) {
  656. return NO;
  657. }
  658. NSString *suppliedFingerprintString = components[3];
  659. if (!suppliedFingerprintString.length) {
  660. return NO;
  661. }
  662. uint64_t suppliedFingerprint;
  663. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  664. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  665. return NO;
  666. }
  667. if ([version isEqual:@"1"]) {
  668. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  669. return YES;
  670. }
  671. // Unknown version.
  672. return NO;
  673. }
  674. - (NSString *)expectedBundleID {
  675. return _options.bundleID;
  676. }
  677. // end App ID validation
  678. #pragma mark - Reading From Plist & User Defaults
  679. /**
  680. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  681. * readability.
  682. */
  683. - (void)clearDataCollectionSwitchFromUserDefaults {
  684. NSString *key =
  685. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  686. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  687. }
  688. /**
  689. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  690. * readability.
  691. */
  692. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  693. // Read the object in user defaults, and only return if it's an NSNumber.
  694. NSString *key =
  695. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  696. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  697. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  698. return collectionEnabledDefaultsObject;
  699. }
  700. return nil;
  701. }
  702. /**
  703. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  704. * only read once from the plist and return the cached value.
  705. */
  706. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  707. static NSNumber *collectionEnabledPlistObject;
  708. static dispatch_once_t onceToken;
  709. dispatch_once(&onceToken, ^{
  710. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  711. id plistValue = [[NSBundle mainBundle]
  712. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  713. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  714. collectionEnabledPlistObject = (NSNumber *)plistValue;
  715. }
  716. });
  717. return collectionEnabledPlistObject;
  718. }
  719. #pragma mark - App Life Cycle
  720. - (void)subscribeForAppDidBecomeActiveNotifications {
  721. #if TARGET_OS_IOS || TARGET_OS_TV
  722. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  723. #elif TARGET_OS_OSX
  724. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  725. #endif
  726. #if !TARGET_OS_WATCH
  727. [[NSNotificationCenter defaultCenter] addObserver:self
  728. selector:@selector(appDidBecomeActive:)
  729. name:notificationName
  730. object:nil];
  731. #endif
  732. }
  733. - (void)appDidBecomeActive:(NSNotification *)notification {
  734. [self logCoreTelemetryIfEnabled];
  735. }
  736. - (void)logCoreTelemetryIfEnabled {
  737. if ([self isDataCollectionDefaultEnabled]) {
  738. dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
  739. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:[self options]];
  740. });
  741. }
  742. }
  743. @end