You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

834 lines
31 KiB

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