FIRApp.m 31 KB

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