FIRApp.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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 "FIRConfiguration.h"
  17. #import "Private/FIRAnalyticsConfiguration+Internal.h"
  18. #import "Private/FIRAppInternal.h"
  19. #import "Private/FIRBundleUtil.h"
  20. #import "Private/FIRComponentContainerInternal.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. + (void)configureWithName:(NSString *)name options:(FIROptions *)options {
  123. if (!name || !options) {
  124. [NSException raise:kFirebaseCoreErrorDomain format:@"Neither name nor options can be nil."];
  125. }
  126. if (name.length == 0) {
  127. [NSException raise:kFirebaseCoreErrorDomain format:@"Name cannot be empty."];
  128. }
  129. if ([name isEqualToString:kFIRDefaultAppName]) {
  130. if (sDefaultApp) {
  131. [NSException raise:kFirebaseCoreErrorDomain
  132. format:@"Default app has already been configured."];
  133. }
  134. FIRLogDebug(kFIRLoggerCore, @"I-COR000001", @"Configuring the default app.");
  135. } else {
  136. // Validate the app name and ensure it hasn't been configured already.
  137. for (NSUInteger charIndex = 0; charIndex < name.length; charIndex++) {
  138. char character = [name characterAtIndex:charIndex];
  139. if (!((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') ||
  140. (character >= '0' && character <= '9') || character == '_' || character == '-')) {
  141. [NSException raise:kFirebaseCoreErrorDomain
  142. format:@"App name should only contain Letters, "
  143. @"Numbers, Underscores, and Dashes."];
  144. }
  145. }
  146. if (sAllApps && sAllApps[name]) {
  147. [NSException raise:kFirebaseCoreErrorDomain
  148. format:@"App named %@ has already been configured.", name];
  149. }
  150. FIRLogDebug(kFIRLoggerCore, @"I-COR000002", @"Configuring app named %@", name);
  151. }
  152. @synchronized(self) {
  153. FIRApp *app = [[FIRApp alloc] initInstanceWithName:name options:options];
  154. if (app.isDefaultApp) {
  155. sDefaultApp = app;
  156. }
  157. [FIRApp addAppToAppDictionary:app];
  158. [FIRApp sendNotificationsToSDKs:app];
  159. }
  160. }
  161. + (FIRApp *)defaultApp {
  162. if (sDefaultApp) {
  163. return sDefaultApp;
  164. }
  165. FIRLogError(kFIRLoggerCore, @"I-COR000003",
  166. @"The default Firebase app has not yet been "
  167. @"configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your "
  168. @"application initialization. Read more: https://goo.gl/ctyzm8.");
  169. return nil;
  170. }
  171. + (FIRApp *)appNamed:(NSString *)name {
  172. @synchronized(self) {
  173. if (sAllApps) {
  174. FIRApp *app = sAllApps[name];
  175. if (app) {
  176. return app;
  177. }
  178. }
  179. FIRLogError(kFIRLoggerCore, @"I-COR000004", @"App with name %@ does not exist.", name);
  180. return nil;
  181. }
  182. }
  183. + (NSDictionary *)allApps {
  184. @synchronized(self) {
  185. if (!sAllApps) {
  186. FIRLogError(kFIRLoggerCore, @"I-COR000005", @"No app has been configured yet.");
  187. }
  188. NSDictionary *dict = [NSDictionary dictionaryWithDictionary:sAllApps];
  189. return dict;
  190. }
  191. }
  192. // Public only for tests
  193. + (void)resetApps {
  194. sDefaultApp = nil;
  195. [sAllApps removeAllObjects];
  196. sAllApps = nil;
  197. [sLibraryVersions removeAllObjects];
  198. sLibraryVersions = nil;
  199. }
  200. - (void)deleteApp:(FIRAppVoidBoolCallback)completion {
  201. @synchronized([self class]) {
  202. if (sAllApps && sAllApps[self.name]) {
  203. FIRLogDebug(kFIRLoggerCore, @"I-COR000006", @"Deleting app named %@", self.name);
  204. // Remove all cached instances from the container before deleting the app.
  205. [self.container removeAllCachedInstances];
  206. [sAllApps removeObjectForKey:self.name];
  207. [self clearDataCollectionSwitchFromUserDefaults];
  208. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  209. sDefaultApp = nil;
  210. }
  211. NSDictionary *appInfoDict = @{kFIRAppNameKey : self.name};
  212. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDeleteNotification
  213. object:[self class]
  214. userInfo:appInfoDict];
  215. completion(YES);
  216. } else {
  217. FIRLogError(kFIRLoggerCore, @"I-COR000007", @"App does not exist.");
  218. completion(NO);
  219. }
  220. }
  221. }
  222. + (void)addAppToAppDictionary:(FIRApp *)app {
  223. if (!sAllApps) {
  224. sAllApps = [NSMutableDictionary dictionary];
  225. }
  226. if ([app configureCore]) {
  227. sAllApps[app.name] = app;
  228. } else {
  229. [NSException raise:kFirebaseCoreErrorDomain
  230. format:@"Configuration fails. It may be caused by an invalid GOOGLE_APP_ID in "
  231. @"GoogleService-Info.plist or set in the customized options."];
  232. }
  233. }
  234. - (instancetype)initInstanceWithName:(NSString *)name options:(FIROptions *)options {
  235. self = [super init];
  236. if (self) {
  237. _name = [name copy];
  238. _options = [options copy];
  239. _options.editingLocked = YES;
  240. _isDefaultApp = [name isEqualToString:kFIRDefaultAppName];
  241. _container = [[FIRComponentContainer alloc] initWithApp:self];
  242. }
  243. return self;
  244. }
  245. - (BOOL)configureCore {
  246. [self checkExpectedBundleID];
  247. if (![self isAppIDValid]) {
  248. if (_options.usingOptionsFromDefaultPlist && [self isDataCollectionDefaultEnabled]) {
  249. [[NSNotificationCenter defaultCenter]
  250. postNotificationName:kFIRAppDiagnosticsNotification
  251. object:nil
  252. userInfo:@{
  253. kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore),
  254. kFIRAppDiagnosticsErrorKey : [FIRApp errorForInvalidAppID],
  255. }];
  256. }
  257. return NO;
  258. }
  259. if ([self isDataCollectionDefaultEnabled]) {
  260. [[NSNotificationCenter defaultCenter]
  261. postNotificationName:kFIRAppDiagnosticsNotification
  262. object:nil
  263. userInfo:@{
  264. kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeCore),
  265. kFIRAppDiagnosticsFIRAppKey : self
  266. }];
  267. }
  268. #if TARGET_OS_IOS
  269. // Initialize the Analytics once there is a valid options under default app. Analytics should
  270. // always initialize first by itself before the other SDKs.
  271. if ([self.name isEqualToString:kFIRDefaultAppName]) {
  272. Class firAnalyticsClass = NSClassFromString(@"FIRAnalytics");
  273. if (!firAnalyticsClass) {
  274. FIRLogWarning(kFIRLoggerCore, @"I-COR000022",
  275. @"Firebase Analytics is not available. To add it, include Firebase/Core in the "
  276. @"Podfile or add FirebaseAnalytics.framework to the Link Build Phase");
  277. } else {
  278. #pragma clang diagnostic push
  279. #pragma clang diagnostic ignored "-Wundeclared-selector"
  280. SEL startWithConfigurationSelector = @selector(startWithConfiguration:options:);
  281. #pragma clang diagnostic pop
  282. if ([firAnalyticsClass respondsToSelector:startWithConfigurationSelector]) {
  283. #pragma clang diagnostic push
  284. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  285. [firAnalyticsClass performSelector:startWithConfigurationSelector
  286. withObject:[FIRConfiguration sharedInstance].analyticsConfiguration
  287. withObject:_options];
  288. #pragma clang diagnostic pop
  289. }
  290. }
  291. }
  292. #endif
  293. return YES;
  294. }
  295. - (FIROptions *)options {
  296. return [_options copy];
  297. }
  298. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  299. #ifdef DEBUG
  300. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  301. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  302. self.alreadyOutputDataCollectionFlag = YES;
  303. #endif // DEBUG
  304. NSString *key =
  305. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  306. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  307. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  308. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  309. // default app, so return if this isn't the default app.
  310. if (!self.isDefaultApp) {
  311. return;
  312. }
  313. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  314. if ([self.options isAnalyticsCollectionExpicitlySet]) {
  315. return;
  316. }
  317. // The Analytics flag has not been explicitly set, so update with the value being set.
  318. [[FIRAnalyticsConfiguration sharedInstance]
  319. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  320. persistSetting:NO];
  321. }
  322. - (BOOL)isDataCollectionDefaultEnabled {
  323. // Check if it's been manually set before in code, and use that as the higher priority value.
  324. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  325. if (defaultsObject != nil) {
  326. #ifdef DEBUG
  327. if (!self.alreadyOutputDataCollectionFlag) {
  328. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  329. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  330. self.alreadyOutputDataCollectionFlag = YES;
  331. }
  332. #endif // DEBUG
  333. return [defaultsObject boolValue];
  334. }
  335. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  336. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  337. // no performance impact calling multiple times.
  338. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  339. if (collectionEnabledPlistValue != nil) {
  340. #ifdef DEBUG
  341. if (!self.alreadyOutputDataCollectionFlag) {
  342. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  343. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  344. self.alreadyOutputDataCollectionFlag = YES;
  345. }
  346. #endif // DEBUG
  347. return [collectionEnabledPlistValue boolValue];
  348. }
  349. #ifdef DEBUG
  350. if (!self.alreadyOutputDataCollectionFlag) {
  351. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  352. self.alreadyOutputDataCollectionFlag = YES;
  353. }
  354. #endif // DEBUG
  355. return YES;
  356. }
  357. #pragma mark - private
  358. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  359. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  360. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  361. NSDictionary *appInfoDict = @{
  362. kFIRAppNameKey : app.name,
  363. kFIRAppIsDefaultAppKey : isDefaultApp,
  364. kFIRGoogleAppIDKey : app.options.googleAppID
  365. };
  366. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  367. object:self
  368. userInfo:appInfoDict];
  369. // This is the new way of sending information to SDKs.
  370. // TODO: Do we want this on a background thread, maybe?
  371. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  372. [library configureWithApp:app];
  373. }
  374. }
  375. + (NSError *)errorForMissingOptions {
  376. NSDictionary *errorDict = @{
  377. NSLocalizedDescriptionKey :
  378. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  379. NSLocalizedRecoverySuggestionErrorKey :
  380. @"Check formatting and location of GoogleService-Info.plist."
  381. };
  382. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  383. code:FIRErrorCodeInvalidPlistFile
  384. userInfo:errorDict];
  385. }
  386. + (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain
  387. errorCode:(FIRErrorCode)code
  388. service:(NSString *)service
  389. reason:(NSString *)reason {
  390. NSString *description =
  391. [NSString stringWithFormat:@"Configuration failed for service %@.", service];
  392. NSDictionary *errorDict =
  393. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  394. return [NSError errorWithDomain:domain code:code userInfo:errorDict];
  395. }
  396. + (NSError *)errorForInvalidAppID {
  397. NSDictionary *errorDict = @{
  398. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  399. NSLocalizedRecoverySuggestionErrorKey :
  400. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  401. @"customized options."
  402. };
  403. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  404. code:FIRErrorCodeInvalidAppID
  405. userInfo:errorDict];
  406. }
  407. + (BOOL)isDefaultAppConfigured {
  408. return (sDefaultApp != nil);
  409. }
  410. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  411. // Create the set of characters which aren't allowed, only if this feature is used.
  412. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  413. [allowedSet addCharactersInString:@"-_."];
  414. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  415. // Make sure the library name and version strings do not contain unexpected characters, and
  416. // add the name/version pair to the dictionary.
  417. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  418. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  419. if (!sLibraryVersions) {
  420. sLibraryVersions = [[NSMutableDictionary alloc] init];
  421. }
  422. sLibraryVersions[name] = version;
  423. } else {
  424. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  425. @"The library name (%@) or version number (%@) contain invalid characters. "
  426. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  427. name, version);
  428. }
  429. }
  430. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  431. withName:(nonnull NSString *)name
  432. withVersion:(nonnull NSString *)version {
  433. // This is called at +load time, keep the work to a minimum.
  434. // Ensure the class given conforms to the proper protocol.
  435. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  436. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  437. [NSException raise:NSInvalidArgumentException
  438. format:@"Class %@ attempted to register components, but it does not conform to "
  439. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  440. library];
  441. }
  442. [FIRComponentContainer registerAsComponentRegistrant:library];
  443. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  444. static dispatch_once_t onceToken;
  445. dispatch_once(&onceToken, ^{
  446. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  447. });
  448. [sRegisteredAsConfigurable addObject:library];
  449. }
  450. [self registerLibrary:name withVersion:version];
  451. }
  452. + (NSString *)firebaseUserAgent {
  453. NSMutableArray<NSString *> *libraries =
  454. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  455. for (NSString *libraryName in sLibraryVersions) {
  456. [libraries
  457. addObject:[NSString stringWithFormat:@"%@/%@", libraryName, sLibraryVersions[libraryName]]];
  458. }
  459. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  460. return [libraries componentsJoinedByString:@" "];
  461. }
  462. - (void)checkExpectedBundleID {
  463. NSArray *bundles = [FIRBundleUtil relevantBundles];
  464. NSString *expectedBundleID = [self expectedBundleID];
  465. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  466. // backward compatibility.
  467. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifier:expectedBundleID
  468. inBundles:bundles]) {
  469. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  470. @"The project's Bundle ID is inconsistent with "
  471. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  472. @"using a customized options. To ensure that everything can be configured "
  473. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  474. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  475. @"download a new configuration file that matches your bundle identifier from %@ "
  476. @"and replace the current one.",
  477. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  478. }
  479. }
  480. #pragma mark - private - App ID Validation
  481. /**
  482. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  483. * This is the main method for validating app ID.
  484. *
  485. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  486. */
  487. - (BOOL)isAppIDValid {
  488. NSString *appID = _options.googleAppID;
  489. BOOL isValid = [FIRApp validateAppID:appID];
  490. if (!isValid) {
  491. NSString *expectedBundleID = [self expectedBundleID];
  492. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  493. @"The GOOGLE_APP_ID either in the plist file "
  494. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  495. @"the plist file, use the iOS version of bundle identifier to download the file, "
  496. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  497. @"identifier to '%@'. Or you can download a new configuration file that matches "
  498. @"your bundle identifier from %@ and replace the current one.",
  499. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  500. };
  501. return isValid;
  502. }
  503. + (BOOL)validateAppID:(NSString *)appID {
  504. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  505. // have a valid fingerprint, otherwise we just warn about the potential issue.
  506. if (!appID.length) {
  507. return NO;
  508. }
  509. // All app IDs must start with at least "<version number>:".
  510. NSString *const versionPattern = @"^\\d+:";
  511. NSRegularExpression *versionRegex =
  512. [NSRegularExpression regularExpressionWithPattern:versionPattern options:0 error:NULL];
  513. if (!versionRegex) {
  514. return NO;
  515. }
  516. NSRange appIDRange = NSMakeRange(0, appID.length);
  517. NSArray *versionMatches = [versionRegex matchesInString:appID options:0 range:appIDRange];
  518. if (versionMatches.count != 1) {
  519. return NO;
  520. }
  521. NSRange versionRange = [(NSTextCheckingResult *)versionMatches.firstObject range];
  522. NSString *appIDVersion = [appID substringWithRange:versionRange];
  523. NSArray *knownVersions = @[ @"1:" ];
  524. if (![knownVersions containsObject:appIDVersion]) {
  525. // Permit unknown yet properly formatted app ID versions.
  526. return YES;
  527. }
  528. if (![FIRApp validateAppIDFormat:appID withVersion:appIDVersion]) {
  529. return NO;
  530. }
  531. if (![FIRApp validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  532. return NO;
  533. }
  534. return YES;
  535. }
  536. + (NSString *)actualBundleID {
  537. return [[NSBundle mainBundle] bundleIdentifier];
  538. }
  539. /**
  540. * Validates that the format of the app ID string is what is expected based on the supplied version.
  541. * The version must end in ":".
  542. *
  543. * For v1 app ids the format is expected to be
  544. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  545. *
  546. * This method does not verify that the contents of the app id are correct, just that they fulfill
  547. * the expected format.
  548. *
  549. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  550. * @param version Indicates what version of the app id format this string should be.
  551. * @return YES if provided string fufills the expected format, NO otherwise.
  552. */
  553. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  554. if (!appID.length || !version.length) {
  555. return NO;
  556. }
  557. if (![version hasSuffix:@":"]) {
  558. return NO;
  559. }
  560. if (![appID hasPrefix:version]) {
  561. return NO;
  562. }
  563. NSString *const pattern = @"^\\d+:ios:[a-f0-9]+$";
  564. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
  565. options:0
  566. error:NULL];
  567. if (!regex) {
  568. return NO;
  569. }
  570. NSRange localRange = NSMakeRange(version.length, appID.length - version.length);
  571. NSUInteger numberOfMatches = [regex numberOfMatchesInString:appID options:0 range:localRange];
  572. if (numberOfMatches != 1) {
  573. return NO;
  574. }
  575. return YES;
  576. }
  577. /**
  578. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  579. * version. The version must end in ":".
  580. *
  581. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  582. *
  583. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  584. * @param version Indicates what version of the app id format this string should be.
  585. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  586. * otherwise.
  587. */
  588. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  589. if (!appID.length || !version.length) {
  590. return NO;
  591. }
  592. if (![version hasSuffix:@":"]) {
  593. return NO;
  594. }
  595. if (![appID hasPrefix:version]) {
  596. return NO;
  597. }
  598. // Extract the supplied fingerprint from the supplied app ID.
  599. // This assumes the app ID format is the same for all known versions below. If the app ID format
  600. // changes in future versions, the tokenizing of the app ID format will need to take into account
  601. // the version of the app ID.
  602. NSArray *components = [appID componentsSeparatedByString:@":"];
  603. if (components.count != 4) {
  604. return NO;
  605. }
  606. NSString *suppliedFingerprintString = components[3];
  607. if (!suppliedFingerprintString.length) {
  608. return NO;
  609. }
  610. uint64_t suppliedFingerprint;
  611. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  612. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  613. return NO;
  614. }
  615. if ([version isEqual:@"1:"]) {
  616. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  617. return YES;
  618. }
  619. // Unknown version.
  620. return NO;
  621. }
  622. - (NSString *)expectedBundleID {
  623. return _options.bundleID;
  624. }
  625. // end App ID validation
  626. #pragma mark - Reading From Plist & User Defaults
  627. /**
  628. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  629. * readability.
  630. */
  631. - (void)clearDataCollectionSwitchFromUserDefaults {
  632. NSString *key =
  633. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  634. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  635. }
  636. /**
  637. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  638. * readability.
  639. */
  640. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  641. // Read the object in user defaults, and only return if it's an NSNumber.
  642. NSString *key =
  643. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  644. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  645. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  646. return collectionEnabledDefaultsObject;
  647. }
  648. return nil;
  649. }
  650. /**
  651. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  652. * only read once from the plist and return the cached value.
  653. */
  654. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  655. static NSNumber *collectionEnabledPlistObject;
  656. static dispatch_once_t onceToken;
  657. dispatch_once(&onceToken, ^{
  658. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  659. id plistValue = [[NSBundle mainBundle]
  660. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  661. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  662. collectionEnabledPlistObject = (NSNumber *)plistValue;
  663. }
  664. });
  665. return collectionEnabledPlistObject;
  666. }
  667. #pragma mark - Sending Logs
  668. - (void)sendLogsWithServiceName:(NSString *)serviceName
  669. version:(NSString *)version
  670. error:(NSError *)error {
  671. // If the user has manually turned off data collection, return and don't send logs.
  672. if (![self isDataCollectionDefaultEnabled]) {
  673. return;
  674. }
  675. NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:@{
  676. kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeSDK),
  677. kFIRAppDiagnosticsSDKNameKey : serviceName,
  678. kFIRAppDiagnosticsSDKVersionKey : version,
  679. kFIRAppDiagnosticsFIRAppKey : self
  680. }];
  681. if (error) {
  682. userInfo[kFIRAppDiagnosticsErrorKey] = error;
  683. }
  684. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDiagnosticsNotification
  685. object:nil
  686. userInfo:userInfo];
  687. }
  688. @end