FIRApp.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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/FIRApp.h>
  22. #import "FirebaseCore/Sources/FIRBundleUtil.h"
  23. #import "FirebaseCore/Sources/FIRVersion.h"
  24. #import "FirebaseCore/Sources/Private/FIRAnalyticsConfiguration.h"
  25. #import "FirebaseCore/Sources/Private/FIRAppInternal.h"
  26. #import "FirebaseCore/Sources/Private/FIRComponentContainerInternal.h"
  27. #import "FirebaseCore/Sources/Private/FIRConfigurationInternal.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 <GoogleUtilities/GULAppEnvironmentUtil.h>
  33. #import <objc/runtime.h>
  34. // The kFIRService strings are only here while transitioning CoreDiagnostics from the Analytics
  35. // pod to a Core dependency. These symbols are not used and should be deleted after the transition.
  36. NSString *const kFIRServiceAdMob;
  37. NSString *const kFIRServiceAuth;
  38. NSString *const kFIRServiceAuthUI;
  39. NSString *const kFIRServiceCrash;
  40. NSString *const kFIRServiceDatabase;
  41. NSString *const kFIRServiceDynamicLinks;
  42. NSString *const kFIRServiceFirestore;
  43. NSString *const kFIRServiceFunctions;
  44. NSString *const kFIRServiceInstanceID;
  45. NSString *const kFIRServiceInvites;
  46. NSString *const kFIRServiceMessaging;
  47. NSString *const kFIRServiceMeasurement;
  48. NSString *const kFIRServicePerformance;
  49. NSString *const kFIRServiceRemoteConfig;
  50. NSString *const kFIRServiceStorage;
  51. NSString *const kGGLServiceAnalytics;
  52. NSString *const kGGLServiceSignIn;
  53. NSString *const kFIRDefaultAppName = @"__FIRAPP_DEFAULT";
  54. NSString *const kFIRAppReadyToConfigureSDKNotification = @"FIRAppReadyToConfigureSDKNotification";
  55. NSString *const kFIRAppDeleteNotification = @"FIRAppDeleteNotification";
  56. NSString *const kFIRAppIsDefaultAppKey = @"FIRAppIsDefaultAppKey";
  57. NSString *const kFIRAppNameKey = @"FIRAppNameKey";
  58. NSString *const kFIRGoogleAppIDKey = @"FIRGoogleAppIDKey";
  59. NSString *const kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat =
  60. @"/google/firebase/global_data_collection_enabled:%@";
  61. NSString *const kFIRGlobalAppDataCollectionEnabledPlistKey =
  62. @"FirebaseDataCollectionDefaultEnabled";
  63. NSString *const kFIRAppDiagnosticsNotification = @"FIRAppDiagnosticsNotification";
  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. * The URL to download plist files.
  81. */
  82. static NSString *const kPlistURL = @"https://console.firebase.google.com/";
  83. /**
  84. * An array of all classes that registered as `FIRCoreConfigurable` in order to receive lifecycle
  85. * events from Core.
  86. */
  87. static NSMutableArray<Class<FIRLibrary>> *sRegisteredAsConfigurable;
  88. @interface FIRApp ()
  89. #ifdef DEBUG
  90. @property(nonatomic) BOOL alreadyOutputDataCollectionFlag;
  91. #endif // DEBUG
  92. @end
  93. @implementation FIRApp
  94. // This is necessary since our custom getter prevents `_options` from being created.
  95. @synthesize options = _options;
  96. static NSMutableDictionary *sAllApps;
  97. static FIRApp *sDefaultApp;
  98. static NSMutableDictionary *sLibraryVersions;
  99. static dispatch_once_t sFirebaseUserAgentOnceToken;
  100. + (void)configure {
  101. FIROptions *options = [FIROptions defaultOptions];
  102. if (!options) {
  103. [NSException raise:kFirebaseCoreErrorDomain
  104. format:@"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) could not find "
  105. @"a valid GoogleService-Info.plist in your project. Please download one "
  106. @"from %@.",
  107. kPlistURL];
  108. }
  109. [FIRApp configureWithOptions:options];
  110. #if TARGET_OS_OSX || TARGET_OS_TV
  111. FIRLogNotice(kFIRLoggerCore, @"I-COR000028",
  112. @"tvOS and macOS SDK support is not part of the official Firebase product. "
  113. @"Instead they are community supported. Details at "
  114. @"https://github.com/firebase/firebase-ios-sdk/blob/master/README.md.");
  115. #endif
  116. }
  117. + (void)configureWithOptions:(FIROptions *)options {
  118. if (!options) {
  119. [NSException raise:kFirebaseCoreErrorDomain
  120. format:@"Options is nil. Please pass a valid options."];
  121. }
  122. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  123. }
  124. + (NSCharacterSet *)applicationNameAllowedCharacters {
  125. static NSCharacterSet *applicationNameAllowedCharacters;
  126. static dispatch_once_t onceToken;
  127. dispatch_once(&onceToken, ^{
  128. NSMutableCharacterSet *allowedNameCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  129. [allowedNameCharacters addCharactersInString:@"-_"];
  130. applicationNameAllowedCharacters = [allowedNameCharacters copy];
  131. });
  132. return applicationNameAllowedCharacters;
  133. }
  134. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  135. if (!name || !options) {
  136. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  137. }
  138. if (name.length == 0) {
  139. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  140. }
  141. if ([name isEqualToString:kFIRDefaultAppName]) {
  142. if (sDefaultApp) {
  143. // The default app already exists. Handle duplicate `configure` calls and return.
  144. [self appWasConfiguredTwice:sDefaultApp usingOptions:options];
  145. return;
  146. }
  147. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  148. } else {
  149. // Validate the app name and ensure it hasn't been configured already.
  150. NSCharacterSet *nameCharacters = [NSCharacterSet characterSetWithCharactersInString:name];
  151. if (![[self applicationNameAllowedCharacters] isSupersetOfSet:nameCharacters]) {
  152. [NSException raise:kFirebaseCoreErrorDomain
  153. format:@"App name can only contain alphanumeric, "
  154. @"hyphen (-), and underscore (_) characters"];
  155. }
  156. @synchronized(self) {
  157. if (sAllApps && sAllApps[name]) {
  158. // The app already exists. Handle a duplicate `configure` call and return.
  159. [self appWasConfiguredTwice:sAllApps[name] usingOptions:options];
  160. return;
  161. }
  162. }
  163. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  164. }
  165. @synchronized(self) {
  166. FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options];
  167. if (app.isDefaultApp) {
  168. sDefaultApp = app;
  169. }
  170. [FIRApp addAppToAppDictionary:app];
  171. // The FIRApp instance is ready to go, `sDefaultApp` is assigned, other SDKs are now ready to be
  172. // instantiated.
  173. [app.container instantiateEagerComponents];
  174. [FIRApp sendNotificationsToSDKs:app];
  175. }
  176. }
  177. /// Called when `configure` has been called multiple times for the same app. This can either throw
  178. /// an exception (most cases) or ignore the duplicate configuration in situations where it's allowed
  179. /// like an extension.
  180. + (void)appWasConfiguredTwice:(FIRApp *)app usingOptions:(FIROptions *)options {
  181. // Only extensions should potentially be able to call `configure` more than once.
  182. if (![GULAppEnvironmentUtil isAppExtension]) {
  183. // Throw an exception since this is now an invalid state.
  184. if (app.isDefaultApp) {
  185. [NSException raise:kFirebaseCoreErrorDomain
  186. format:@"Default app has already been configured."];
  187. } else {
  188. [NSException raise:kFirebaseCoreErrorDomain
  189. format:@"App named %@ has already been configured.", app.name];
  190. }
  191. }
  192. // In an extension, the entry point could be called multiple times. As long as the options are
  193. // identical we should allow multiple `configure` calls.
  194. if ([options isEqual:app.options]) {
  195. // Everything is identical but the extension's lifecycle triggered `configure` twice.
  196. // Ignore duplicate calls and return since everything should still be in a valid state.
  197. FIRLogDebug(kFIRLoggerCore, @"I-COR000035",
  198. @"Ignoring second `configure` call in an extension.");
  199. return;
  200. } else {
  201. [NSException raise:kFirebaseCoreErrorDomain
  202. format:@"App named %@ has already been configured.", app.name];
  203. }
  204. }
  205. + (FIRApp *)defaultApp {
  206. if (sDefaultApp) {
  207. return sDefaultApp;
  208. }
  209. FIRLogError(kFIRLoggerCore, @"I-COR000003",
  210. @"The default Firebase app has not yet been "
  211. @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your "
  212. @"application initialization. Read more: https://goo.gl/ctyzm8.");
  213. return nil;
  214. }
  215. + (FIRApp *)appNamed:(NSString *)name {
  216. @synchronized(self) {
  217. if (sAllApps) {
  218. FIRApp *app = sAllApps[name];
  219. if (app) {
  220. return app;
  221. }
  222. }
  223. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  224. return nil;
  225. }
  226. }
  227. + (NSDictionary *)allApps {
  228. @synchronized(self) {
  229. if (!sAllApps) {
  230. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  231. }
  232. return [sAllApps copy];
  233. }
  234. }
  235. // Public only for tests
  236. + (void)resetApps {
  237. @synchronized(self) {
  238. sDefaultApp = nil;
  239. [sAllApps removeAllObjects];
  240. sAllApps = nil;
  241. [sLibraryVersions removeAllObjects];
  242. sLibraryVersions = nil;
  243. sFirebaseUserAgentOnceToken = 0;
  244. }
  245. }
  246. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  247. @synchronized([self class]) {
  248. if (sAllApps && sAllApps[self.name]) {
  249. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  250. // Remove all registered libraries from the container to avoid creating new instances.
  251. [self.container removeAllComponents];
  252. // Remove all cached instances from the container before deleting the app.
  253. [self.container removeAllCachedInstances];
  254. [sAllApps removeObjectForKey:self.name];
  255. [self clearDataCollectionSwitchFromUserDefaults];
  256. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  257. sDefaultApp = nil;
  258. }
  259. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  260. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  261. object:[self class]
  262. userInfo:appInfoDict];
  263. completion(YES);
  264. } else {
  265. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  266. completion(NO);
  267. }
  268. }
  269. }
  270. + (void)addAppToAppDictionary:(FIRApp *)app {
  271. if (!sAllApps) {
  272. sAllApps = [NSMutableDictionary dictionary];
  273. }
  274. if ([app configureCore]) {
  275. sAllApps[app.name] = app;
  276. } else {
  277. [NSException raise:kFirebaseCoreErrorDomain
  278. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  279. @"GoogleService-Info.plist or set in the customized options."];
  280. }
  281. }
  282. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  283. self = [super init];
  284. if (self) {
  285. _name = [name copy];
  286. _options = [options copy];
  287. _options.editingLocked = YES;
  288. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  289. _container = [[FIRComponentContainer alloc] initWithApp:self];
  290. }
  291. return self;
  292. }
  293. - (void)dealloc {
  294. [[NSNotificationCenter defaultCenter] removeObserver:self];
  295. }
  296. - (BOOL)configureCore {
  297. [self checkExpectedBundleID];
  298. if (![self isAppIDValid]) {
  299. return NO;
  300. }
  301. [self logCoreTelemetryIfEnabled];
  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
  420. code:FIRErrorCodeInvalidPlistFile
  421. userInfo:errorDict];
  422. }
  423. + (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain
  424. errorCode:(FIRErrorCode)code
  425. service:(NSString *)service
  426. reason:(NSString *)reason {
  427. NSString *description =
  428. [NSString stringWithFormat:@"Configuration failed for service %@.", service];
  429. NSDictionary *errorDict =
  430. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  431. return [NSError errorWithDomain:domain code:code userInfo:errorDict];
  432. }
  433. + (NSError *)errorForInvalidAppID {
  434. NSDictionary *errorDict = @{
  435. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  436. NSLocalizedRecoverySuggestionErrorKey :
  437. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  438. @"customized options."
  439. };
  440. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  441. code:FIRErrorCodeInvalidAppID
  442. userInfo:errorDict];
  443. }
  444. + (BOOL)isDefaultAppConfigured {
  445. return (sDefaultApp != nil);
  446. }
  447. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  448. // Create the set of characters which aren't allowed, only if this feature is used.
  449. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  450. [allowedSet addCharactersInString:@"-_."];
  451. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  452. // Make sure the library name and version strings do not contain unexpected characters, and
  453. // add the name/version pair to the dictionary.
  454. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  455. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  456. @synchronized(self) {
  457. if (!sLibraryVersions) {
  458. sLibraryVersions = [[NSMutableDictionary alloc] init];
  459. }
  460. sLibraryVersions[name] = version;
  461. }
  462. } else {
  463. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  464. @"The library name (%@) or version number (%@) contain invalid characters. "
  465. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  466. name, version);
  467. }
  468. }
  469. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  470. withName:(nonnull NSString *)name
  471. withVersion:(nonnull NSString *)version {
  472. // This is called at +load time, keep the work to a minimum.
  473. // Ensure the class given conforms to the proper protocol.
  474. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  475. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  476. [NSException raise:NSInvalidArgumentException
  477. format:@"Class %@ attempted to register components, but it does not conform to "
  478. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  479. library];
  480. }
  481. [FIRComponentContainer registerAsComponentRegistrant:library];
  482. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  483. static dispatch_once_t onceToken;
  484. dispatch_once(&onceToken, ^{
  485. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  486. });
  487. @synchronized(self) {
  488. [sRegisteredAsConfigurable addObject:library];
  489. }
  490. }
  491. [self registerLibrary:name withVersion:version];
  492. }
  493. + (NSString *)firebaseUserAgent {
  494. @synchronized(self) {
  495. dispatch_once(&sFirebaseUserAgentOnceToken, ^{
  496. // Report FirebaseCore version for useragent string
  497. [FIRApp registerLibrary:@"fire-ios"
  498. withVersion:[NSString stringWithUTF8String:FIRCoreVersionString]];
  499. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  500. NSString *xcodeVersion = info[@"DTXcodeBuild"];
  501. NSString *sdkVersion = info[@"DTSDKBuild"];
  502. if (xcodeVersion) {
  503. [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion];
  504. }
  505. if (sdkVersion) {
  506. [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion];
  507. }
  508. NSString *swiftFlagValue = [self hasSwiftRuntime] ? @"true" : @"false";
  509. [FIRApp registerLibrary:@"swift" withVersion:swiftFlagValue];
  510. [FIRApp registerLibrary:kFIRAppDiagnosticsApplePlatformPrefix
  511. withVersion:[self applePlatform]];
  512. });
  513. NSMutableArray<NSString *> *libraries =
  514. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  515. for (NSString *libraryName in sLibraryVersions) {
  516. [libraries addObject:[NSString stringWithFormat:@"%@/%@", libraryName,
  517. sLibraryVersions[libraryName]]];
  518. }
  519. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  520. return [libraries componentsJoinedByString:@" "];
  521. }
  522. }
  523. + (BOOL)hasSwiftRuntime {
  524. // The class
  525. // [Swift._SwiftObject](https://github.com/apple/swift/blob/5eac3e2818eb340b11232aff83edfbd1c307fa03/stdlib/public/runtime/SwiftObject.h#L35)
  526. // is a part of Swift runtime, so it should be present if Swift runtime is available.
  527. BOOL hasSwiftRuntime =
  528. objc_lookUpClass("Swift._SwiftObject") != nil ||
  529. // Swift object class name before
  530. // https://github.com/apple/swift/commit/9637b4a6e11ddca72f5f6dbe528efc7c92f14d01
  531. objc_getClass("_TtCs12_SwiftObject") != nil;
  532. return hasSwiftRuntime;
  533. }
  534. + (NSString *)applePlatform {
  535. NSString *applePlatform = @"unknown";
  536. // When a Catalyst app is run on macOS then both `TARGET_OS_MACCATALYST` and `TARGET_OS_IOS` are
  537. // `true`, which means the condition list is order-sensitive.
  538. #if TARGET_OS_MACCATALYST
  539. applePlatform = @"maccatalyst";
  540. #elif TARGET_OS_IOS
  541. applePlatform = @"ios";
  542. #elif TARGET_OS_TV
  543. applePlatform = @"tvos";
  544. #elif TARGET_OS_OSX
  545. applePlatform = @"macos";
  546. #elif TARGET_OS_WATCH
  547. applePlatform = @"watchos";
  548. #endif
  549. return applePlatform;
  550. }
  551. - (void)checkExpectedBundleID {
  552. NSArray *bundles = [FIRBundleUtil relevantBundles];
  553. NSString *expectedBundleID = [self expectedBundleID];
  554. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  555. // backward compatibility.
  556. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  557. inBundles:bundles]) {
  558. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  559. @"The project's Bundle ID is inconsistent with "
  560. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  561. @"using a customized options. To ensure that everything can be configured "
  562. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  563. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  564. @"download a new configuration file that matches your bundle identifier from %@ "
  565. @"and replace the current one.",
  566. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  567. }
  568. }
  569. #pragma mark - private - App ID Validation
  570. /**
  571. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  572. * This is the main method for validating app ID.
  573. *
  574. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  575. */
  576. - (BOOL)isAppIDValid {
  577. NSString *appID = _options.googleAppID;
  578. BOOL isValid = [FIRApp validateAppID:appID];
  579. if (!isValid) {
  580. NSString *expectedBundleID = [self expectedBundleID];
  581. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  582. @"The GOOGLE_APP_ID either in the plist file "
  583. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  584. @"the plist file, use the iOS version of bundle identifier to download the file, "
  585. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  586. @"identifier to '%@'. Or you can download a new configuration file that matches "
  587. @"your bundle identifier from %@ and replace the current one.",
  588. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  589. };
  590. return isValid;
  591. }
  592. + (BOOL)validateAppID:(NSString *)appID {
  593. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  594. // have a valid fingerprint, otherwise we just warn about the potential issue.
  595. if (!appID.length) {
  596. return NO;
  597. }
  598. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  599. stringScanner.charactersToBeSkipped = nil;
  600. NSString *appIDVersion;
  601. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  602. intoString:&appIDVersion]) {
  603. return NO;
  604. }
  605. if (![stringScanner scanString:@":" intoString:NULL]) {
  606. // appIDVersion must be separated by ":"
  607. return NO;
  608. }
  609. NSArray *knownVersions = @[ @"1" ];
  610. if (![knownVersions containsObject:appIDVersion]) {
  611. // Permit unknown yet properly formatted app ID versions.
  612. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  613. return YES;
  614. }
  615. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  616. return NO;
  617. }
  618. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  619. return NO;
  620. }
  621. return YES;
  622. }
  623. + (NSString *)actualBundleID {
  624. return [[NSBundle mainBundle] bundleIdentifier];
  625. }
  626. /**
  627. * Validates that the format of the app ID string is what is expected based on the supplied version.
  628. * The version must end in ":".
  629. *
  630. * For v1 app ids the format is expected to be
  631. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  632. *
  633. * This method does not verify that the contents of the app id are correct, just that they fulfill
  634. * the expected format.
  635. *
  636. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  637. * @param version Indicates what version of the app id format this string should be.
  638. * @return YES if provided string fufills the expected format, NO otherwise.
  639. */
  640. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  641. if (!appID.length || !version.length) {
  642. return NO;
  643. }
  644. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  645. stringScanner.charactersToBeSkipped = nil;
  646. // Skip version part
  647. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  648. if (![stringScanner scanString:version intoString:NULL]) {
  649. // The version part is missing or mismatched
  650. return NO;
  651. }
  652. // Validate version part (see part between '*' symbols below)
  653. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  654. if (![stringScanner scanString:@":" intoString:NULL]) {
  655. // appIDVersion must be separated by ":"
  656. return NO;
  657. }
  658. // Validate version part (see part between '*' symbols below)
  659. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  660. NSInteger projectNumber = NSNotFound;
  661. if (![stringScanner scanInteger:&projectNumber]) {
  662. // NO project number found.
  663. return NO;
  664. }
  665. // Validate version part (see part between '*' symbols below)
  666. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  667. if (![stringScanner scanString:@":" intoString:NULL]) {
  668. // The project number must be separated by ":"
  669. return NO;
  670. }
  671. // Validate version part (see part between '*' symbols below)
  672. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  673. NSString *platform;
  674. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  675. return NO;
  676. }
  677. if (![platform isEqualToString:@"ios"]) {
  678. // The platform must be @"ios"
  679. return NO;
  680. }
  681. // Validate version part (see part between '*' symbols below)
  682. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  683. if (![stringScanner scanString:@":" intoString:NULL]) {
  684. // The platform must be separated by ":"
  685. return NO;
  686. }
  687. // Validate version part (see part between '*' symbols below)
  688. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  689. unsigned long long fingerprint = NSNotFound;
  690. if (![stringScanner scanHexLongLong:&fingerprint]) {
  691. // Fingerprint part is missing
  692. return NO;
  693. }
  694. if (!stringScanner.isAtEnd) {
  695. // There are not allowed characters in the fingerprint part
  696. return NO;
  697. }
  698. return YES;
  699. }
  700. /**
  701. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  702. * version.
  703. *
  704. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  705. *
  706. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  707. * @param version Indicates what version of the app id format this string should be.
  708. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  709. * otherwise.
  710. */
  711. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  712. // Extract the supplied fingerprint from the supplied app ID.
  713. // This assumes the app ID format is the same for all known versions below. If the app ID format
  714. // changes in future versions, the tokenizing of the app ID format will need to take into account
  715. // the version of the app ID.
  716. NSArray *components = [appID componentsSeparatedByString:@":"];
  717. if (components.count != 4) {
  718. return NO;
  719. }
  720. NSString *suppliedFingerprintString = components[3];
  721. if (!suppliedFingerprintString.length) {
  722. return NO;
  723. }
  724. uint64_t suppliedFingerprint;
  725. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  726. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  727. return NO;
  728. }
  729. if ([version isEqual:@"1"]) {
  730. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  731. return YES;
  732. }
  733. // Unknown version.
  734. return NO;
  735. }
  736. - (NSString *)expectedBundleID {
  737. return _options.bundleID;
  738. }
  739. // end App ID validation
  740. #pragma mark - Reading From Plist & User Defaults
  741. /**
  742. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  743. * readability.
  744. */
  745. - (void)clearDataCollectionSwitchFromUserDefaults {
  746. NSString *key =
  747. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  748. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  749. }
  750. /**
  751. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  752. * readability.
  753. */
  754. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  755. // Read the object in user defaults, and only return if it's an NSNumber.
  756. NSString *key =
  757. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  758. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  759. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  760. return collectionEnabledDefaultsObject;
  761. }
  762. return nil;
  763. }
  764. /**
  765. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  766. * only read once from the plist and return the cached value.
  767. */
  768. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  769. static NSNumber *collectionEnabledPlistObject;
  770. static dispatch_once_t onceToken;
  771. dispatch_once(&onceToken, ^{
  772. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  773. id plistValue = [[NSBundle mainBundle]
  774. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  775. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  776. collectionEnabledPlistObject = (NSNumber *)plistValue;
  777. }
  778. });
  779. return collectionEnabledPlistObject;
  780. }
  781. #pragma mark - Sending Logs
  782. #pragma clang diagnostic push
  783. #pragma clang diagnostic ignored "-Wunused-parameter"
  784. - (void)sendLogsWithServiceName:(NSString *)serviceName
  785. version:(NSString *)version
  786. error:(NSError *)error {
  787. // Do nothing. Please remove calls to this method.
  788. }
  789. #pragma clang diagnostic pop
  790. #pragma mark - App Life Cycle
  791. - (void)subscribeForAppDidBecomeActiveNotifications {
  792. #if TARGET_OS_IOS || TARGET_OS_TV
  793. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  794. #elif TARGET_OS_OSX
  795. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  796. #endif
  797. #if !TARGET_OS_WATCH
  798. [[NSNotificationCenter defaultCenter] addObserver:self
  799. selector:@selector(appDidBecomeActive:)
  800. name:notificationName
  801. object:nil];
  802. #endif
  803. }
  804. - (void)appDidBecomeActive:(NSNotification *)notification {
  805. [self logCoreTelemetryIfEnabled];
  806. }
  807. - (void)logCoreTelemetryIfEnabled {
  808. if ([self isDataCollectionDefaultEnabled]) {
  809. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:_options];
  810. }
  811. }
  812. @end