FIRApp.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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 kFIRAppDiagnosticsNotification = @"FIRAppDiagnosticsNotification";
  65. NSString *const kFIRAppDiagnosticsConfigurationTypeKey = @"ConfigType";
  66. NSString *const kFIRAppDiagnosticsErrorKey = @"Error";
  67. NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRApp";
  68. NSString *const kFIRAppDiagnosticsSDKNameKey = @"SDKName";
  69. NSString *const kFIRAppDiagnosticsSDKVersionKey = @"SDKVersion";
  70. NSString *const kFIRAppDiagnosticsApplePlatformPrefix = @"apple-platform";
  71. // Auth internal notification notification and key.
  72. NSString *const FIRAuthStateDidChangeInternalNotification =
  73. @"FIRAuthStateDidChangeInternalNotification";
  74. NSString *const FIRAuthStateDidChangeInternalNotificationAppKey =
  75. @"FIRAuthStateDidChangeInternalNotificationAppKey";
  76. NSString *const FIRAuthStateDidChangeInternalNotificationTokenKey =
  77. @"FIRAuthStateDidChangeInternalNotificationTokenKey";
  78. NSString *const FIRAuthStateDidChangeInternalNotificationUIDKey =
  79. @"FIRAuthStateDidChangeInternalNotificationUIDKey";
  80. /**
  81. * Error domain for exceptions and NSError construction.
  82. */
  83. NSString *const kFirebaseCoreErrorDomain = @"com.firebase.core";
  84. /**
  85. * The URL to download plist files.
  86. */
  87. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  88. /**
  89. * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle
  90. * events from Core.
  91. */
  92. static NSMutableArray<Class<FIRLibrary>> *sRegisteredAsConfigurable;
  93. @interface FIRApp ()
  94. #ifdef DEBUG
  95. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  96. #endif // DEBUG
  97. @end
  98. @implementation FIRApp
  99. // This is necessary since our custom getter prevents `_options` from being created.
  100. @synthesize options = _options;
  101. static NSMutableDictionary *sAllApps;
  102. static FIRApp *sDefaultApp;
  103. + (void)configure {
  104. FIROptions *options = [FIROptions defaultOptions];
  105. if (!options) {
  106. [NSException raise:kFirebaseCoreErrorDomain
  107. format:@"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find "
  108. @"a valid GoogleService-Info.plist in your project. Please download one "
  109. @"from %@.",
  110. kPlistURL];
  111. }
  112. [FIRApp configureWithOptions:options];
  113. #if TARGET_OS_OSX || TARGET_OS_TV
  114. FIRLogNotice(kFIRLoggerCore, @"I-COR000028",
  115. @"tvOS and macOS SDK support is not part of the official Firebase product. "
  116. @"Instead they are community supported. Details at "
  117. @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md.");
  118. #endif
  119. }
  120. + (void)configureWithOptions:(FIROptions *)options {
  121. if (!options) {
  122. [NSException raise:kFirebaseCoreErrorDomain
  123. format:@"Options is nil. Please pass a valid options."];
  124. }
  125. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  126. }
  127. + (NSCharacterSet *)applicationNameAllowedCharacters {
  128. static NSCharacterSet *applicationNameAllowedCharacters;
  129. static dispatch_once_t onceToken;
  130. dispatch_once(&onceToken, ^{
  131. NSMutableCharacterSet *allowedNameCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  132. [allowedNameCharacters addCharactersInString:@"-_"];
  133. applicationNameAllowedCharacters = [allowedNameCharacters copy];
  134. });
  135. return applicationNameAllowedCharacters;
  136. }
  137. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  138. if (!name || !options) {
  139. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  140. }
  141. if (name.length == 0) {
  142. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  143. }
  144. if ([name isEqualToString:kFIRDefaultAppName]) {
  145. if (sDefaultApp) {
  146. // The default app already exists. Handle duplicate `configure` calls and return.
  147. [self appWasConfiguredTwice:sDefaultApp usingOptions:options];
  148. return;
  149. }
  150. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  151. } else {
  152. // Validate the app name and ensure it hasn't been configured already.
  153. NSCharacterSet *nameCharacters = [NSCharacterSet characterSetWithCharactersInString:name];
  154. if (![[self applicationNameAllowedCharacters] isSupersetOfSet:nameCharacters]) {
  155. [NSException raise:kFirebaseCoreErrorDomain
  156. format:@"App name can only contain alphanumeric, "
  157. @"hyphen (-), and underscore (_) characters"];
  158. }
  159. @synchronized(self) {
  160. if (sAllApps && sAllApps[name]) {
  161. // The app already exists. Handle a duplicate `configure` call and return.
  162. [self appWasConfiguredTwice:sAllApps[name] usingOptions:options];
  163. return;
  164. }
  165. }
  166. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  167. }
  168. @synchronized(self) {
  169. FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options];
  170. if (app.isDefaultApp) {
  171. sDefaultApp = app;
  172. }
  173. [FIRApp addAppToAppDictionary:app];
  174. // The FIRApp instance is ready to go, `sDefaultApp` is assigned, other SDKs are now ready to be
  175. // instantiated.
  176. [app.container instantiateEagerComponents];
  177. [FIRApp sendNotificationsToSDKs:app];
  178. }
  179. }
  180. /// Called when `configure` has been called multiple times for the same app. This can either throw
  181. /// an exception (most cases) or ignore the duplicate configuration in situations where it's allowed
  182. /// like an extension.
  183. + (void)appWasConfiguredTwice:(FIRApp *)app usingOptions:(FIROptions *)options {
  184. // Only extensions should potentially be able to call `configure` more than once.
  185. if (![GULAppEnvironmentUtil isAppExtension]) {
  186. // Throw an exception since this is now an invalid state.
  187. if (app.isDefaultApp) {
  188. [NSException raise:kFirebaseCoreErrorDomain
  189. format:@"Default app has already been configured."];
  190. } else {
  191. [NSException raise:kFirebaseCoreErrorDomain
  192. format:@"App named %@ has already been configured.", app.name];
  193. }
  194. }
  195. // In an extension, the entry point could be called multiple times. As long as the options are
  196. // identical we should allow multiple `configure` calls.
  197. if ([options isEqual:app.options]) {
  198. // Everything is identical but the extension's lifecycle triggered `configure` twice.
  199. // Ignore duplicate calls and return since everything should still be in a valid state.
  200. FIRLogDebug(kFIRLoggerCore, @"I-COR000035",
  201. @"Ignoring second `configure` call in an extension.");
  202. return;
  203. } else {
  204. [NSException raise:kFirebaseCoreErrorDomain
  205. format:@"App named %@ has already been configured.", app.name];
  206. }
  207. }
  208. + (FIRApp *)defaultApp {
  209. if (sDefaultApp) {
  210. return sDefaultApp;
  211. }
  212. FIRLogError(kFIRLoggerCore, @"I-COR000003",
  213. @"The default Firebase app has not yet been "
  214. @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your "
  215. @"application initialization. Read more: https://goo.gl/ctyzm8.");
  216. return nil;
  217. }
  218. + (FIRApp *)appNamed:(NSString *)name {
  219. @synchronized(self) {
  220. if (sAllApps) {
  221. FIRApp *app = sAllApps[name];
  222. if (app) {
  223. return app;
  224. }
  225. }
  226. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  227. return nil;
  228. }
  229. }
  230. + (NSDictionary *)allApps {
  231. @synchronized(self) {
  232. if (!sAllApps) {
  233. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  234. }
  235. return [sAllApps copy];
  236. }
  237. }
  238. // Public only for tests
  239. + (void)resetApps {
  240. @synchronized(self) {
  241. sDefaultApp = nil;
  242. [sAllApps removeAllObjects];
  243. sAllApps = nil;
  244. [[self userAgent] reset];
  245. }
  246. }
  247. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  248. @synchronized([self class]) {
  249. if (sAllApps && sAllApps[self.name]) {
  250. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  251. // Remove all registered libraries from the container to avoid creating new instances.
  252. [self.container removeAllComponents];
  253. // Remove all cached instances from the container before deleting the app.
  254. [self.container removeAllCachedInstances];
  255. [sAllApps removeObjectForKey:self.name];
  256. [self clearDataCollectionSwitchFromUserDefaults];
  257. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  258. sDefaultApp = nil;
  259. }
  260. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  261. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  262. object:[self class]
  263. userInfo:appInfoDict];
  264. completion(YES);
  265. } else {
  266. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  267. completion(NO);
  268. }
  269. }
  270. }
  271. + (void)addAppToAppDictionary:(FIRApp *)app {
  272. if (!sAllApps) {
  273. sAllApps = [NSMutableDictionary dictionary];
  274. }
  275. if ([app configureCore]) {
  276. sAllApps[app.name] = app;
  277. } else {
  278. [NSException raise:kFirebaseCoreErrorDomain
  279. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  280. @"GoogleService-Info.plist or set in the customized options."];
  281. }
  282. }
  283. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  284. self = [super init];
  285. if (self) {
  286. _name = [name copy];
  287. _options = [options copy];
  288. _options.editingLocked = YES;
  289. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  290. _container = [[FIRComponentContainer alloc] initWithApp:self];
  291. }
  292. return self;
  293. }
  294. - (void)dealloc {
  295. [[NSNotificationCenter defaultCenter] removeObserver:self];
  296. }
  297. - (BOOL)configureCore {
  298. [self checkExpectedBundleID];
  299. if (![self isAppIDValid]) {
  300. return NO;
  301. }
  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. // Check if it's been manually set before in code, and use that as the higher priority value.
  359. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  360. if (defaultsObject != nil) {
  361. #ifdef DEBUG
  362. if (!self.alreadyOutputDataCollectionFlag) {
  363. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  364. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  365. self.alreadyOutputDataCollectionFlag = YES;
  366. }
  367. #endif // DEBUG
  368. return [defaultsObject boolValue];
  369. }
  370. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  371. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  372. // no performance impact calling multiple times.
  373. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  374. if (collectionEnabledPlistValue != nil) {
  375. #ifdef DEBUG
  376. if (!self.alreadyOutputDataCollectionFlag) {
  377. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  378. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  379. self.alreadyOutputDataCollectionFlag = YES;
  380. }
  381. #endif // DEBUG
  382. return [collectionEnabledPlistValue boolValue];
  383. }
  384. #ifdef DEBUG
  385. if (!self.alreadyOutputDataCollectionFlag) {
  386. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  387. self.alreadyOutputDataCollectionFlag = YES;
  388. }
  389. #endif // DEBUG
  390. return YES;
  391. }
  392. #pragma mark - private
  393. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  394. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  395. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  396. NSDictionary *appInfoDict = @{
  397. kFIRAppNameKey : app.name,
  398. kFIRAppIsDefaultAppKey : isDefaultApp,
  399. kFIRGoogleAppIDKey : app.options.googleAppID
  400. };
  401. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  402. object:self
  403. userInfo:appInfoDict];
  404. // This is the new way of sending information to SDKs.
  405. // TODO: Do we want this on a background thread, maybe?
  406. @synchronized(self) {
  407. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  408. [library configureWithApp:app];
  409. }
  410. }
  411. }
  412. + (NSError *)errorForMissingOptions {
  413. NSDictionary *errorDict = @{
  414. NSLocalizedDescriptionKey :
  415. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  416. NSLocalizedRecoverySuggestionErrorKey :
  417. @"Check formatting and location of GoogleService-Info.plist."
  418. };
  419. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-100 userInfo:errorDict];
  420. }
  421. + (NSError *)errorForInvalidAppID {
  422. NSDictionary *errorDict = @{
  423. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  424. NSLocalizedRecoverySuggestionErrorKey :
  425. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  426. @"customized options."
  427. };
  428. return [NSError errorWithDomain:kFirebaseCoreErrorDomain code:-101 userInfo:errorDict];
  429. }
  430. + (BOOL)isDefaultAppConfigured {
  431. return (sDefaultApp != nil);
  432. }
  433. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  434. // Create the set of characters which aren't allowed, only if this feature is used.
  435. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  436. [allowedSet addCharactersInString:@"-_."];
  437. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  438. // Make sure the library name and version strings do not contain unexpected characters, and
  439. // add the name/version pair to the dictionary.
  440. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  441. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  442. [[self userAgent] setValue:version forComponent:name];
  443. } else {
  444. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  445. @"The library name (%@) or version number (%@) contain invalid characters. "
  446. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  447. name, version);
  448. }
  449. }
  450. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  451. withName:(nonnull NSString *)name {
  452. [self registerInternalLibrary:library withName:name withVersion:FIRFirebaseVersion()];
  453. }
  454. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  455. withName:(nonnull NSString *)name
  456. withVersion:(nonnull NSString *)version {
  457. // This is called at +load time, keep the work to a minimum.
  458. // Ensure the class given conforms to the proper protocol.
  459. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  460. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  461. [NSException raise:NSInvalidArgumentException
  462. format:@"Class %@ attempted to register components, but it does not conform to "
  463. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  464. library];
  465. }
  466. [FIRComponentContainer registerAsComponentRegistrant:library];
  467. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  468. static dispatch_once_t onceToken;
  469. dispatch_once(&onceToken, ^{
  470. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  471. });
  472. @synchronized(self) {
  473. [sRegisteredAsConfigurable addObject:library];
  474. }
  475. }
  476. [self registerLibrary:name withVersion:version];
  477. }
  478. + (FIRFirebaseUserAgent *)userAgent {
  479. static dispatch_once_t onceToken;
  480. static FIRFirebaseUserAgent *_userAgent;
  481. dispatch_once(&onceToken, ^{
  482. _userAgent = [[FIRFirebaseUserAgent alloc] init];
  483. [_userAgent setValue:FIRFirebaseVersion() forComponent:@"fire-ios"];
  484. });
  485. return _userAgent;
  486. }
  487. + (NSString *)firebaseUserAgent {
  488. return [[self userAgent] firebaseUserAgent];
  489. }
  490. - (void)checkExpectedBundleID {
  491. NSArray *bundles = [FIRBundleUtil relevantBundles];
  492. NSString *expectedBundleID = [self expectedBundleID];
  493. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  494. // backward compatibility.
  495. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  496. inBundles:bundles]) {
  497. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  498. @"The project's Bundle ID is inconsistent with "
  499. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  500. @"using a customized options. To ensure that everything can be configured "
  501. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  502. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  503. @"download a new configuration file that matches your bundle identifier from %@ "
  504. @"and replace the current one.",
  505. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  506. }
  507. }
  508. #pragma mark - private - App ID Validation
  509. /**
  510. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  511. * This is the main method for validating app ID.
  512. *
  513. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  514. */
  515. - (BOOL)isAppIDValid {
  516. NSString *appID = _options.googleAppID;
  517. BOOL isValid = [FIRApp validateAppID:appID];
  518. if (!isValid) {
  519. NSString *expectedBundleID = [self expectedBundleID];
  520. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  521. @"The GOOGLE_APP_ID either in the plist file "
  522. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  523. @"the plist file, use the iOS version of bundle identifier to download the file, "
  524. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  525. @"identifier to '%@'. Or you can download a new configuration file that matches "
  526. @"your bundle identifier from %@ and replace the current one.",
  527. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  528. };
  529. return isValid;
  530. }
  531. + (BOOL)validateAppID:(NSString *)appID {
  532. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  533. // have a valid fingerprint, otherwise we just warn about the potential issue.
  534. if (!appID.length) {
  535. return NO;
  536. }
  537. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  538. stringScanner.charactersToBeSkipped = nil;
  539. NSString *appIDVersion;
  540. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  541. intoString:&appIDVersion]) {
  542. return NO;
  543. }
  544. if (![stringScanner scanString:@":" intoString:NULL]) {
  545. // appIDVersion must be separated by ":"
  546. return NO;
  547. }
  548. NSArray *knownVersions = @[ @"1" ];
  549. if (![knownVersions containsObject:appIDVersion]) {
  550. // Permit unknown yet properly formatted app ID versions.
  551. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  552. return YES;
  553. }
  554. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  555. return NO;
  556. }
  557. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  558. return NO;
  559. }
  560. return YES;
  561. }
  562. + (NSString *)actualBundleID {
  563. return [[NSBundle mainBundle] bundleIdentifier];
  564. }
  565. /**
  566. * Validates that the format of the app ID string is what is expected based on the supplied version.
  567. * The version must end in ":".
  568. *
  569. * For v1 app ids the format is expected to be
  570. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  571. *
  572. * This method does not verify that the contents of the app id are correct, just that they fulfill
  573. * the expected format.
  574. *
  575. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  576. * @param version Indicates what version of the app id format this string should be.
  577. * @return YES if provided string fufills the expected format, NO otherwise.
  578. */
  579. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  580. if (!appID.length || !version.length) {
  581. return NO;
  582. }
  583. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  584. stringScanner.charactersToBeSkipped = nil;
  585. // Skip version part
  586. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  587. if (![stringScanner scanString:version intoString:NULL]) {
  588. // The version part is missing or mismatched
  589. return NO;
  590. }
  591. // Validate version part (see part between '*' symbols below)
  592. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  593. if (![stringScanner scanString:@":" intoString:NULL]) {
  594. // appIDVersion must be separated by ":"
  595. return NO;
  596. }
  597. // Validate version part (see part between '*' symbols below)
  598. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  599. NSInteger projectNumber = NSNotFound;
  600. if (![stringScanner scanInteger:&projectNumber]) {
  601. // NO project number found.
  602. return NO;
  603. }
  604. // Validate version part (see part between '*' symbols below)
  605. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  606. if (![stringScanner scanString:@":" intoString:NULL]) {
  607. // The project number must be separated by ":"
  608. return NO;
  609. }
  610. // Validate version part (see part between '*' symbols below)
  611. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  612. NSString *platform;
  613. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  614. return NO;
  615. }
  616. if (![platform isEqualToString:@"ios"]) {
  617. // The platform must be @"ios"
  618. return NO;
  619. }
  620. // Validate version part (see part between '*' symbols below)
  621. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  622. if (![stringScanner scanString:@":" intoString:NULL]) {
  623. // The platform must be separated by ":"
  624. return NO;
  625. }
  626. // Validate version part (see part between '*' symbols below)
  627. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  628. unsigned long long fingerprint = NSNotFound;
  629. if (![stringScanner scanHexLongLong:&fingerprint]) {
  630. // Fingerprint part is missing
  631. return NO;
  632. }
  633. if (!stringScanner.isAtEnd) {
  634. // There are not allowed characters in the fingerprint part
  635. return NO;
  636. }
  637. return YES;
  638. }
  639. /**
  640. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  641. * version.
  642. *
  643. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  644. *
  645. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  646. * @param version Indicates what version of the app id format this string should be.
  647. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  648. * otherwise.
  649. */
  650. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  651. // Extract the supplied fingerprint from the supplied app ID.
  652. // This assumes the app ID format is the same for all known versions below. If the app ID format
  653. // changes in future versions, the tokenizing of the app ID format will need to take into account
  654. // the version of the app ID.
  655. NSArray *components = [appID componentsSeparatedByString:@":"];
  656. if (components.count != 4) {
  657. return NO;
  658. }
  659. NSString *suppliedFingerprintString = components[3];
  660. if (!suppliedFingerprintString.length) {
  661. return NO;
  662. }
  663. uint64_t suppliedFingerprint;
  664. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  665. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  666. return NO;
  667. }
  668. if ([version isEqual:@"1"]) {
  669. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  670. return YES;
  671. }
  672. // Unknown version.
  673. return NO;
  674. }
  675. - (NSString *)expectedBundleID {
  676. return _options.bundleID;
  677. }
  678. // end App ID validation
  679. #pragma mark - Reading From Plist & User Defaults
  680. /**
  681. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  682. * readability.
  683. */
  684. - (void)clearDataCollectionSwitchFromUserDefaults {
  685. NSString *key =
  686. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  687. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  688. }
  689. /**
  690. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  691. * readability.
  692. */
  693. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  694. // Read the object in user defaults, and only return if it's an NSNumber.
  695. NSString *key =
  696. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  697. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  698. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  699. return collectionEnabledDefaultsObject;
  700. }
  701. return nil;
  702. }
  703. /**
  704. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  705. * only read once from the plist and return the cached value.
  706. */
  707. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  708. static NSNumber *collectionEnabledPlistObject;
  709. static dispatch_once_t onceToken;
  710. dispatch_once(&onceToken, ^{
  711. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  712. id plistValue = [[NSBundle mainBundle]
  713. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  714. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  715. collectionEnabledPlistObject = (NSNumber *)plistValue;
  716. }
  717. });
  718. return collectionEnabledPlistObject;
  719. }
  720. #pragma mark - App Life Cycle
  721. - (void)subscribeForAppDidBecomeActiveNotifications {
  722. #if TARGET_OS_IOS || TARGET_OS_TV
  723. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  724. #elif TARGET_OS_OSX
  725. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  726. #endif
  727. #if !TARGET_OS_WATCH
  728. [[NSNotificationCenter defaultCenter] addObserver:self
  729. selector:@selector(appDidBecomeActive:)
  730. name:notificationName
  731. object:nil];
  732. #endif
  733. }
  734. - (void)appDidBecomeActive:(NSNotification *)notification {
  735. [self logCoreTelemetryIfEnabled];
  736. }
  737. - (void)logCoreTelemetryIfEnabled {
  738. if ([self isDataCollectionDefaultEnabled]) {
  739. dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
  740. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:[self options]];
  741. });
  742. }
  743. }
  744. @end