FIRApp.m 32 KB

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