FIRApp.m 34 KB

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