FIRApp.m 31 KB

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