No Description

FIRApp.m 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. #import "Private/FIRVersion.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 cached instances from the container before deleting the app.
  250. [self.container removeAllCachedInstances];
  251. [sAllApps removeObjectForKey:self.name];
  252. [self clearDataCollectionSwitchFromUserDefaults];
  253. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  254. sDefaultApp = nil;
  255. }
  256. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  257. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  258. object:[self class]
  259. userInfo:appInfoDict];
  260. completion(YES);
  261. } else {
  262. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  263. completion(NO);
  264. }
  265. }
  266. }
  267. + (void)addAppToAppDictionary:(FIRApp *)app {
  268. if (!sAllApps) {
  269. sAllApps = [NSMutableDictionary dictionary];
  270. }
  271. if ([app configureCore]) {
  272. sAllApps[app.name] = app;
  273. } else {
  274. [NSException raise:kFirebaseCoreErrorDomain
  275. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  276. @"GoogleService-Info.plist or set in the customized options."];
  277. }
  278. }
  279. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  280. self = [super init];
  281. if (self) {
  282. _name = [name copy];
  283. _options = [options copy];
  284. _options.editingLocked = YES;
  285. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  286. _container = [[FIRComponentContainer alloc] initWithApp:self];
  287. }
  288. return self;
  289. }
  290. - (void)dealloc {
  291. [[NSNotificationCenter defaultCenter] removeObserver:self];
  292. }
  293. - (BOOL)configureCore {
  294. [self checkExpectedBundleID];
  295. if (![self isAppIDValid]) {
  296. return NO;
  297. }
  298. [self logCoreTelemetryIfEnabled];
  299. #if TARGET_OS_IOS
  300. // Initialize the Analytics once there is a valid options under default app. Analytics should
  301. // always initialize first by itself before the other SDKs.
  302. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  303. Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics");
  304. if (firAnalyticsClass) {
  305. #pragma clang diagnostic push
  306. #pragma clang diagnostic ignored "-Wundeclared-selector"
  307. SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:);
  308. #pragma clang diagnostic pop
  309. if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) {
  310. #pragma clang diagnostic push
  311. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  312. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  313. [firAnalyticsClass performSelector:startWithConfigurationSelector
  314. withObject:[FIRConfiguration sharedInstance].analyticsConfiguration
  315. withObject:_options];
  316. #pragma clang diagnostic pop
  317. }
  318. }
  319. }
  320. #endif
  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
  417. code:FIRErrorCodeInvalidPlistFile
  418. userInfo:errorDict];
  419. }
  420. + (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain
  421. errorCode:(FIRErrorCode)code
  422. service:(NSString *)service
  423. reason:(NSString *)reason {
  424. NSString *description =
  425. [NSString stringWithFormat:@"Configuration failed for service %@.", service];
  426. NSDictionary *errorDict =
  427. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  428. return [NSError errorWithDomain:domain code:code userInfo:errorDict];
  429. }
  430. + (NSError *)errorForInvalidAppID {
  431. NSDictionary *errorDict = @{
  432. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  433. NSLocalizedRecoverySuggestionErrorKey :
  434. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  435. @"customized options."
  436. };
  437. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  438. code:FIRErrorCodeInvalidAppID
  439. userInfo:errorDict];
  440. }
  441. + (BOOL)isDefaultAppConfigured {
  442. return (sDefaultApp != nil);
  443. }
  444. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  445. // Create the set of characters which aren't allowed, only if this feature is used.
  446. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  447. [allowedSet addCharactersInString:@"-_."];
  448. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  449. // Make sure the library name and version strings do not contain unexpected characters, and
  450. // add the name/version pair to the dictionary.
  451. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  452. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  453. @synchronized(self) {
  454. if (!sLibraryVersions) {
  455. sLibraryVersions = [[NSMutableDictionary alloc] init];
  456. }
  457. sLibraryVersions[name] = version;
  458. }
  459. } else {
  460. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  461. @"The library name (%@) or version number (%@) contain invalid characters. "
  462. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  463. name, version);
  464. }
  465. }
  466. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  467. withName:(nonnull NSString *)name
  468. withVersion:(nonnull NSString *)version {
  469. // This is called at +load time, keep the work to a minimum.
  470. // Ensure the class given conforms to the proper protocol.
  471. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  472. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  473. [NSException raise:NSInvalidArgumentException
  474. format:@"Class %@ attempted to register components, but it does not conform to "
  475. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  476. library];
  477. }
  478. [FIRComponentContainer registerAsComponentRegistrant:library];
  479. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  480. static dispatch_once_t onceToken;
  481. dispatch_once(&onceToken, ^{
  482. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  483. });
  484. @synchronized(self) {
  485. [sRegisteredAsConfigurable addObject:library];
  486. }
  487. }
  488. [self registerLibrary:name withVersion:version];
  489. }
  490. + (NSString *)firebaseUserAgent {
  491. @synchronized(self) {
  492. dispatch_once(&sFirebaseUserAgentOnceToken, ^{
  493. // Report FirebaseCore version for useragent string
  494. [FIRApp registerLibrary:@"fire-ios"
  495. withVersion:[NSString stringWithUTF8String:FIRCoreVersionString]];
  496. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  497. NSString *xcodeVersion = info[@"DTXcodeBuild"];
  498. NSString *sdkVersion = info[@"DTSDKBuild"];
  499. if (xcodeVersion) {
  500. [FIRApp registerLibrary:@"xcode" withVersion:xcodeVersion];
  501. }
  502. if (sdkVersion) {
  503. [FIRApp registerLibrary:@"apple-sdk" withVersion:sdkVersion];
  504. }
  505. NSString *swiftFlagValue = [self hasSwiftRuntime] ? @"true" : @"false";
  506. [FIRApp registerLibrary:@"swift" withVersion:swiftFlagValue];
  507. });
  508. NSMutableArray<NSString *> *libraries =
  509. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  510. for (NSString *libraryName in sLibraryVersions) {
  511. [libraries addObject:[NSString stringWithFormat:@"%@/%@", libraryName,
  512. sLibraryVersions[libraryName]]];
  513. }
  514. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  515. return [libraries componentsJoinedByString:@" "];
  516. }
  517. }
  518. + (BOOL)hasSwiftRuntime {
  519. // The class
  520. // [Swift._SwiftObject](https://github.com/apple/swift/blob/5eac3e2818eb340b11232aff83edfbd1c307fa03/stdlib/public/runtime/SwiftObject.h#L35)
  521. // is a part of Swift runtime, so it should be present if Swift runtime is available.
  522. BOOL hasSwiftRuntime =
  523. objc_lookUpClass("Swift._SwiftObject") != nil ||
  524. // Swift object class name before
  525. // https://github.com/apple/swift/commit/9637b4a6e11ddca72f5f6dbe528efc7c92f14d01
  526. objc_getClass("_TtCs12_SwiftObject") != nil;
  527. return hasSwiftRuntime;
  528. }
  529. - (void)checkExpectedBundleID {
  530. NSArray *bundles = [FIRBundleUtil relevantBundles];
  531. NSString *expectedBundleID = [self expectedBundleID];
  532. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  533. // backward compatibility.
  534. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  535. inBundles:bundles]) {
  536. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  537. @"The project's Bundle ID is inconsistent with "
  538. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  539. @"using a customized options. To ensure that everything can be configured "
  540. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  541. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  542. @"download a new configuration file that matches your bundle identifier from %@ "
  543. @"and replace the current one.",
  544. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  545. }
  546. }
  547. #pragma mark - private - App ID Validation
  548. /**
  549. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  550. * This is the main method for validating app ID.
  551. *
  552. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  553. */
  554. - (BOOL)isAppIDValid {
  555. NSString *appID = _options.googleAppID;
  556. BOOL isValid = [FIRApp validateAppID:appID];
  557. if (!isValid) {
  558. NSString *expectedBundleID = [self expectedBundleID];
  559. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  560. @"The GOOGLE_APP_ID either in the plist file "
  561. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  562. @"the plist file, use the iOS version of bundle identifier to download the file, "
  563. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  564. @"identifier to '%@'. Or you can download a new configuration file that matches "
  565. @"your bundle identifier from %@ and replace the current one.",
  566. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  567. };
  568. return isValid;
  569. }
  570. + (BOOL)validateAppID:(NSString *)appID {
  571. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  572. // have a valid fingerprint, otherwise we just warn about the potential issue.
  573. if (!appID.length) {
  574. return NO;
  575. }
  576. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  577. stringScanner.charactersToBeSkipped = nil;
  578. NSString *appIDVersion;
  579. if (![stringScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet]
  580. intoString:&appIDVersion]) {
  581. return NO;
  582. }
  583. if (![stringScanner scanString:@":" intoString:NULL]) {
  584. // appIDVersion must be separated by ":"
  585. return NO;
  586. }
  587. NSArray *knownVersions = @[ @"1" ];
  588. if (![knownVersions containsObject:appIDVersion]) {
  589. // Permit unknown yet properly formatted app ID versions.
  590. FIRLogInfo(kFIRLoggerCore, @"I-COR000010", @"Unknown GOOGLE_APP_ID version: %@", appIDVersion);
  591. return YES;
  592. }
  593. if (![self validateAppIDFormat:appID withVersion:appIDVersion]) {
  594. return NO;
  595. }
  596. if (![self validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  597. return NO;
  598. }
  599. return YES;
  600. }
  601. + (NSString *)actualBundleID {
  602. return [[NSBundle mainBundle] bundleIdentifier];
  603. }
  604. /**
  605. * Validates that the format of the app ID string is what is expected based on the supplied version.
  606. * The version must end in ":".
  607. *
  608. * For v1 app ids the format is expected to be
  609. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  610. *
  611. * This method does not verify that the contents of the app id are correct, just that they fulfill
  612. * the expected format.
  613. *
  614. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  615. * @param version Indicates what version of the app id format this string should be.
  616. * @return YES if provided string fufills the expected format, NO otherwise.
  617. */
  618. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  619. if (!appID.length || !version.length) {
  620. return NO;
  621. }
  622. NSScanner *stringScanner = [NSScanner scannerWithString:appID];
  623. stringScanner.charactersToBeSkipped = nil;
  624. // Skip version part
  625. // '*<version #>*:<project number>:ios:<fingerprint of bundle id>'
  626. if (![stringScanner scanString:version intoString:NULL]) {
  627. // The version part is missing or mismatched
  628. return NO;
  629. }
  630. // Validate version part (see part between '*' symbols below)
  631. // '<version #>*:*<project number>:ios:<fingerprint of bundle id>'
  632. if (![stringScanner scanString:@":" intoString:NULL]) {
  633. // appIDVersion must be separated by ":"
  634. return NO;
  635. }
  636. // Validate version part (see part between '*' symbols below)
  637. // '<version #>:*<project number>*:ios:<fingerprint of bundle id>'.
  638. NSInteger projectNumber = NSNotFound;
  639. if (![stringScanner scanInteger:&projectNumber]) {
  640. // NO project number found.
  641. return NO;
  642. }
  643. // Validate version part (see part between '*' symbols below)
  644. // '<version #>:<project number>*:*ios:<fingerprint of bundle id>'.
  645. if (![stringScanner scanString:@":" intoString:NULL]) {
  646. // The project number must be separated by ":"
  647. return NO;
  648. }
  649. // Validate version part (see part between '*' symbols below)
  650. // '<version #>:<project number>:*ios*:<fingerprint of bundle id>'.
  651. NSString *platform;
  652. if (![stringScanner scanUpToString:@":" intoString:&platform]) {
  653. return NO;
  654. }
  655. if (![platform isEqualToString:@"ios"]) {
  656. // The platform must be @"ios"
  657. return NO;
  658. }
  659. // Validate version part (see part between '*' symbols below)
  660. // '<version #>:<project number>:ios*:*<fingerprint of bundle id>'.
  661. if (![stringScanner scanString:@":" intoString:NULL]) {
  662. // The platform must be separated by ":"
  663. return NO;
  664. }
  665. // Validate version part (see part between '*' symbols below)
  666. // '<version #>:<project number>:ios:*<fingerprint of bundle id>*'.
  667. unsigned long long fingerprint = NSNotFound;
  668. if (![stringScanner scanHexLongLong:&fingerprint]) {
  669. // Fingerprint part is missing
  670. return NO;
  671. }
  672. if (!stringScanner.isAtEnd) {
  673. // There are not allowed characters in the fingerprint part
  674. return NO;
  675. }
  676. return YES;
  677. }
  678. /**
  679. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  680. * version.
  681. *
  682. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  683. *
  684. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  685. * @param version Indicates what version of the app id format this string should be.
  686. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  687. * otherwise.
  688. */
  689. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  690. // Extract the supplied fingerprint from the supplied app ID.
  691. // This assumes the app ID format is the same for all known versions below. If the app ID format
  692. // changes in future versions, the tokenizing of the app ID format will need to take into account
  693. // the version of the app ID.
  694. NSArray *components = [appID componentsSeparatedByString:@":"];
  695. if (components.count != 4) {
  696. return NO;
  697. }
  698. NSString *suppliedFingerprintString = components[3];
  699. if (!suppliedFingerprintString.length) {
  700. return NO;
  701. }
  702. uint64_t suppliedFingerprint;
  703. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  704. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  705. return NO;
  706. }
  707. if ([version isEqual:@"1"]) {
  708. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  709. return YES;
  710. }
  711. // Unknown version.
  712. return NO;
  713. }
  714. - (NSString *)expectedBundleID {
  715. return _options.bundleID;
  716. }
  717. // end App ID validation
  718. #pragma mark - Reading From Plist & User Defaults
  719. /**
  720. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  721. * readability.
  722. */
  723. - (void)clearDataCollectionSwitchFromUserDefaults {
  724. NSString *key =
  725. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  726. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  727. }
  728. /**
  729. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  730. * readability.
  731. */
  732. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  733. // Read the object in user defaults, and only return if it's an NSNumber.
  734. NSString *key =
  735. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  736. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  737. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  738. return collectionEnabledDefaultsObject;
  739. }
  740. return nil;
  741. }
  742. /**
  743. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  744. * only read once from the plist and return the cached value.
  745. */
  746. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  747. static NSNumber *collectionEnabledPlistObject;
  748. static dispatch_once_t onceToken;
  749. dispatch_once(&onceToken, ^{
  750. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  751. id plistValue = [[NSBundle mainBundle]
  752. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  753. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  754. collectionEnabledPlistObject = (NSNumber *)plistValue;
  755. }
  756. });
  757. return collectionEnabledPlistObject;
  758. }
  759. #pragma mark - Sending Logs
  760. #pragma clang diagnostic push
  761. #pragma clang diagnostic ignored "-Wunused-parameter"
  762. - (void)sendLogsWithServiceName:(NSString *)serviceName
  763. version:(NSString *)version
  764. error:(NSError *)error {
  765. // Do nothing. Please remove calls to this method.
  766. }
  767. #pragma clang diagnostic pop
  768. #pragma mark - App Life Cycle
  769. - (void)subscribeForAppDidBecomeActiveNotifications {
  770. #if TARGET_OS_IOS || TARGET_OS_TV
  771. NSNotificationName notificationName = UIApplicationDidBecomeActiveNotification;
  772. #endif
  773. #if TARGET_OS_OSX
  774. NSNotificationName notificationName = NSApplicationDidBecomeActiveNotification;
  775. #endif
  776. [[NSNotificationCenter defaultCenter] addObserver:self
  777. selector:@selector(appDidBecomeActive:)
  778. name:notificationName
  779. object:nil];
  780. }
  781. - (void)appDidBecomeActive:(NSNotification *)notification {
  782. [self logCoreTelemetryIfEnabled];
  783. }
  784. - (void)logCoreTelemetryIfEnabled {
  785. if ([self isDataCollectionDefaultEnabled]) {
  786. [FIRCoreDiagnosticsConnector logCoreTelemetryWithOptions:_options];
  787. }
  788. }
  789. @end