FIRApp.m 32 KB

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