No Description

FIRApp.m 30KB

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