No Description

FIRApp.m 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  286. [firAnalyticsClass performSelector:startWithConfigurationSelector
  287. withObject:[FIRConfiguration sharedInstance].analyticsConfiguration
  288. withObject:_options];
  289. #pragma clang diagnostic pop
  290. }
  291. }
  292. }
  293. #endif
  294. return YES;
  295. }
  296. - (FIROptions *)options {
  297. return [_options copy];
  298. }
  299. - (void)setDataCollectionDefaultEnabled:(BOOL)dataCollectionDefaultEnabled {
  300. #ifdef DEBUG
  301. FIRLogDebug(kFIRLoggerCore, @"I-COR000034", @"Explicitly %@ data collection flag.",
  302. dataCollectionDefaultEnabled ? @"enabled" : @"disabled");
  303. self.alreadyOutputDataCollectionFlag = YES;
  304. #endif // DEBUG
  305. NSString *key =
  306. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  307. [[NSUserDefaults standardUserDefaults] setBool:dataCollectionDefaultEnabled forKey:key];
  308. // Core also controls the FirebaseAnalytics flag, so check if the Analytics flags are set
  309. // within FIROptions and change the Analytics value if necessary. Analytics only works with the
  310. // default app, so return if this isn't the default app.
  311. if (!self.isDefaultApp) {
  312. return;
  313. }
  314. // Check if the Analytics flag is explicitly set. If so, no further actions are necessary.
  315. if ([self.options isAnalyticsCollectionExpicitlySet]) {
  316. return;
  317. }
  318. // The Analytics flag has not been explicitly set, so update with the value being set.
  319. #pragma clang diagnostic push
  320. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  321. [[FIRAnalyticsConfiguration sharedInstance]
  322. setAnalyticsCollectionEnabled:dataCollectionDefaultEnabled
  323. persistSetting:NO];
  324. #pragma clang diagnostic pop
  325. }
  326. - (BOOL)isDataCollectionDefaultEnabled {
  327. // Check if it's been manually set before in code, and use that as the higher priority value.
  328. NSNumber *defaultsObject = [[self class] readDataCollectionSwitchFromUserDefaultsForApp:self];
  329. if (defaultsObject != nil) {
  330. #ifdef DEBUG
  331. if (!self.alreadyOutputDataCollectionFlag) {
  332. FIRLogDebug(kFIRLoggerCore, @"I-COR000031", @"Data Collection flag is %@ in user defaults.",
  333. [defaultsObject boolValue] ? @"enabled" : @"disabled");
  334. self.alreadyOutputDataCollectionFlag = YES;
  335. }
  336. #endif // DEBUG
  337. return [defaultsObject boolValue];
  338. }
  339. // Read the Info.plist to see if the flag is set. If it's not set, it should default to `YES`.
  340. // As per the implementation of `readDataCollectionSwitchFromPlist`, it's a cached value and has
  341. // no performance impact calling multiple times.
  342. NSNumber *collectionEnabledPlistValue = [[self class] readDataCollectionSwitchFromPlist];
  343. if (collectionEnabledPlistValue != nil) {
  344. #ifdef DEBUG
  345. if (!self.alreadyOutputDataCollectionFlag) {
  346. FIRLogDebug(kFIRLoggerCore, @"I-COR000032", @"Data Collection flag is %@ in plist.",
  347. [collectionEnabledPlistValue boolValue] ? @"enabled" : @"disabled");
  348. self.alreadyOutputDataCollectionFlag = YES;
  349. }
  350. #endif // DEBUG
  351. return [collectionEnabledPlistValue boolValue];
  352. }
  353. #ifdef DEBUG
  354. if (!self.alreadyOutputDataCollectionFlag) {
  355. FIRLogDebug(kFIRLoggerCore, @"I-COR000033", @"Data Collection flag is not set.");
  356. self.alreadyOutputDataCollectionFlag = YES;
  357. }
  358. #endif // DEBUG
  359. return YES;
  360. }
  361. #pragma mark - private
  362. + (void)sendNotificationsToSDKs:(FIRApp *)app {
  363. // TODO: Remove this notification once all SDKs are registered with `FIRCoreConfigurable`.
  364. NSNumber *isDefaultApp = [NSNumber numberWithBool:app.isDefaultApp];
  365. NSDictionary *appInfoDict = @{
  366. kFIRAppNameKey : app.name,
  367. kFIRAppIsDefaultAppKey : isDefaultApp,
  368. kFIRGoogleAppIDKey : app.options.googleAppID
  369. };
  370. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppReadyToConfigureSDKNotification
  371. object:self
  372. userInfo:appInfoDict];
  373. // This is the new way of sending information to SDKs.
  374. // TODO: Do we want this on a background thread, maybe?
  375. for (Class<FIRLibrary> library in sRegisteredAsConfigurable) {
  376. [library configureWithApp:app];
  377. }
  378. }
  379. + (NSError *)errorForMissingOptions {
  380. NSDictionary *errorDict = @{
  381. NSLocalizedDescriptionKey :
  382. @"Unable to parse GoogleService-Info.plist in order to configure services.",
  383. NSLocalizedRecoverySuggestionErrorKey :
  384. @"Check formatting and location of GoogleService-Info.plist."
  385. };
  386. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  387. code:FIRErrorCodeInvalidPlistFile
  388. userInfo:errorDict];
  389. }
  390. + (NSError *)errorForSubspecConfigurationFailureWithDomain:(NSString *)domain
  391. errorCode:(FIRErrorCode)code
  392. service:(NSString *)service
  393. reason:(NSString *)reason {
  394. NSString *description =
  395. [NSString stringWithFormat:@"Configuration failed for service %@.", service];
  396. NSDictionary *errorDict =
  397. @{NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason};
  398. return [NSError errorWithDomain:domain code:code userInfo:errorDict];
  399. }
  400. + (NSError *)errorForInvalidAppID {
  401. NSDictionary *errorDict = @{
  402. NSLocalizedDescriptionKey : @"Unable to validate Google App ID",
  403. NSLocalizedRecoverySuggestionErrorKey :
  404. @"Check formatting and location of GoogleService-Info.plist or GoogleAppID set in the "
  405. @"customized options."
  406. };
  407. return [NSError errorWithDomain:kFirebaseCoreErrorDomain
  408. code:FIRErrorCodeInvalidAppID
  409. userInfo:errorDict];
  410. }
  411. + (BOOL)isDefaultAppConfigured {
  412. return (sDefaultApp != nil);
  413. }
  414. + (void)registerLibrary:(nonnull NSString *)name withVersion:(nonnull NSString *)version {
  415. // Create the set of characters which aren't allowed, only if this feature is used.
  416. NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet alphanumericCharacterSet];
  417. [allowedSet addCharactersInString:@"-_."];
  418. NSCharacterSet *disallowedSet = [allowedSet invertedSet];
  419. // Make sure the library name and version strings do not contain unexpected characters, and
  420. // add the name/version pair to the dictionary.
  421. if ([name rangeOfCharacterFromSet:disallowedSet].location == NSNotFound &&
  422. [version rangeOfCharacterFromSet:disallowedSet].location == NSNotFound) {
  423. if (!sLibraryVersions) {
  424. sLibraryVersions = [[NSMutableDictionary alloc] init];
  425. }
  426. sLibraryVersions[name] = version;
  427. } else {
  428. FIRLogError(kFIRLoggerCore, @"I-COR000027",
  429. @"The library name (%@) or version number (%@) contain invalid characters. "
  430. @"Only alphanumeric, dash, underscore and period characters are allowed.",
  431. name, version);
  432. }
  433. }
  434. + (void)registerInternalLibrary:(nonnull Class<FIRLibrary>)library
  435. withName:(nonnull NSString *)name
  436. withVersion:(nonnull NSString *)version {
  437. // This is called at +load time, keep the work to a minimum.
  438. // Ensure the class given conforms to the proper protocol.
  439. if (![(Class)library conformsToProtocol:@protocol(FIRLibrary)] ||
  440. ![(Class)library respondsToSelector:@selector(componentsToRegister)]) {
  441. [NSException raise:NSInvalidArgumentException
  442. format:@"Class %@ attempted to register components, but it does not conform to "
  443. @"`FIRLibrary or provide a `componentsToRegister:` method.",
  444. library];
  445. }
  446. [FIRComponentContainer registerAsComponentRegistrant:library];
  447. if ([(Class)library respondsToSelector:@selector(configureWithApp:)]) {
  448. static dispatch_once_t onceToken;
  449. dispatch_once(&onceToken, ^{
  450. sRegisteredAsConfigurable = [[NSMutableArray alloc] init];
  451. });
  452. [sRegisteredAsConfigurable addObject:library];
  453. }
  454. [self registerLibrary:name withVersion:version];
  455. }
  456. + (NSString *)firebaseUserAgent {
  457. NSMutableArray<NSString *> *libraries =
  458. [[NSMutableArray<NSString *> alloc] initWithCapacity:sLibraryVersions.count];
  459. for (NSString *libraryName in sLibraryVersions) {
  460. [libraries
  461. addObject:[NSString stringWithFormat:@"%@/%@", libraryName, sLibraryVersions[libraryName]]];
  462. }
  463. [libraries sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
  464. return [libraries componentsJoinedByString:@" "];
  465. }
  466. - (void)checkExpectedBundleID {
  467. NSArray *bundles = [FIRBundleUtil relevantBundles];
  468. NSString *expectedBundleID = [self expectedBundleID];
  469. // The checking is only done when the bundle ID is provided in the serviceInfo dictionary for
  470. // backward compatibility.
  471. if (expectedBundleID != nil && ![FIRBundleUtil hasBundleIdentifierPrefix:expectedBundleID
  472. inBundles:bundles]) {
  473. FIRLogError(kFIRLoggerCore, @"I-COR000008",
  474. @"The project's Bundle ID is inconsistent with "
  475. @"either the Bundle ID in '%@.%@', or the Bundle ID in the options if you are "
  476. @"using a customized options. To ensure that everything can be configured "
  477. @"correctly, you may need to make the Bundle IDs consistent. To continue with this "
  478. @"plist file, you may change your app's bundle identifier to '%@'. Or you can "
  479. @"download a new configuration file that matches your bundle identifier from %@ "
  480. @"and replace the current one.",
  481. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  482. }
  483. }
  484. #pragma mark - private - App ID Validation
  485. /**
  486. * Validates the format and fingerprint of the app ID contained in GOOGLE_APP_ID in the plist file.
  487. * This is the main method for validating app ID.
  488. *
  489. * @return YES if the app ID fulfills the expected format and fingerprint, NO otherwise.
  490. */
  491. - (BOOL)isAppIDValid {
  492. NSString *appID = _options.googleAppID;
  493. BOOL isValid = [FIRApp validateAppID:appID];
  494. if (!isValid) {
  495. NSString *expectedBundleID = [self expectedBundleID];
  496. FIRLogError(kFIRLoggerCore, @"I-COR000009",
  497. @"The GOOGLE_APP_ID either in the plist file "
  498. @"'%@.%@' or the one set in the customized options is invalid. If you are using "
  499. @"the plist file, use the iOS version of bundle identifier to download the file, "
  500. @"and do not manually edit the GOOGLE_APP_ID. You may change your app's bundle "
  501. @"identifier to '%@'. Or you can download a new configuration file that matches "
  502. @"your bundle identifier from %@ and replace the current one.",
  503. kServiceInfoFileName, kServiceInfoFileType, expectedBundleID, kPlistURL);
  504. };
  505. return isValid;
  506. }
  507. + (BOOL)validateAppID:(NSString *)appID {
  508. // Failing validation only occurs when we are sure we are looking at a V2 app ID and it does not
  509. // have a valid fingerprint, otherwise we just warn about the potential issue.
  510. if (!appID.length) {
  511. return NO;
  512. }
  513. // All app IDs must start with at least "<version number>:".
  514. NSString *const versionPattern = @"^\\d+:";
  515. NSRegularExpression *versionRegex =
  516. [NSRegularExpression regularExpressionWithPattern:versionPattern options:0 error:NULL];
  517. if (!versionRegex) {
  518. return NO;
  519. }
  520. NSRange appIDRange = NSMakeRange(0, appID.length);
  521. NSArray *versionMatches = [versionRegex matchesInString:appID options:0 range:appIDRange];
  522. if (versionMatches.count != 1) {
  523. return NO;
  524. }
  525. NSRange versionRange = [(NSTextCheckingResult *)versionMatches.firstObject range];
  526. NSString *appIDVersion = [appID substringWithRange:versionRange];
  527. NSArray *knownVersions = @[ @"1:" ];
  528. if (![knownVersions containsObject:appIDVersion]) {
  529. // Permit unknown yet properly formatted app ID versions.
  530. return YES;
  531. }
  532. if (![FIRApp validateAppIDFormat:appID withVersion:appIDVersion]) {
  533. return NO;
  534. }
  535. if (![FIRApp validateAppIDFingerprint:appID withVersion:appIDVersion]) {
  536. return NO;
  537. }
  538. return YES;
  539. }
  540. + (NSString *)actualBundleID {
  541. return [[NSBundle mainBundle] bundleIdentifier];
  542. }
  543. /**
  544. * Validates that the format of the app ID string is what is expected based on the supplied version.
  545. * The version must end in ":".
  546. *
  547. * For v1 app ids the format is expected to be
  548. * '<version #>:<project number>:ios:<fingerprint of bundle id>'.
  549. *
  550. * This method does not verify that the contents of the app id are correct, just that they fulfill
  551. * the expected format.
  552. *
  553. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  554. * @param version Indicates what version of the app id format this string should be.
  555. * @return YES if provided string fufills the expected format, NO otherwise.
  556. */
  557. + (BOOL)validateAppIDFormat:(NSString *)appID withVersion:(NSString *)version {
  558. if (!appID.length || !version.length) {
  559. return NO;
  560. }
  561. if (![version hasSuffix:@":"]) {
  562. return NO;
  563. }
  564. if (![appID hasPrefix:version]) {
  565. return NO;
  566. }
  567. NSString *const pattern = @"^\\d+:ios:[a-f0-9]+$";
  568. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
  569. options:0
  570. error:NULL];
  571. if (!regex) {
  572. return NO;
  573. }
  574. NSRange localRange = NSMakeRange(version.length, appID.length - version.length);
  575. NSUInteger numberOfMatches = [regex numberOfMatchesInString:appID options:0 range:localRange];
  576. if (numberOfMatches != 1) {
  577. return NO;
  578. }
  579. return YES;
  580. }
  581. /**
  582. * Validates that the fingerprint of the app ID string is what is expected based on the supplied
  583. * version. The version must end in ":".
  584. *
  585. * Note that the v1 hash algorithm is not permitted on the client and cannot be fully validated.
  586. *
  587. * @param appID Contents of GOOGLE_APP_ID from the plist file.
  588. * @param version Indicates what version of the app id format this string should be.
  589. * @return YES if provided string fufills the expected fingerprint and the version is known, NO
  590. * otherwise.
  591. */
  592. + (BOOL)validateAppIDFingerprint:(NSString *)appID withVersion:(NSString *)version {
  593. if (!appID.length || !version.length) {
  594. return NO;
  595. }
  596. if (![version hasSuffix:@":"]) {
  597. return NO;
  598. }
  599. if (![appID hasPrefix:version]) {
  600. return NO;
  601. }
  602. // Extract the supplied fingerprint from the supplied app ID.
  603. // This assumes the app ID format is the same for all known versions below. If the app ID format
  604. // changes in future versions, the tokenizing of the app ID format will need to take into account
  605. // the version of the app ID.
  606. NSArray *components = [appID componentsSeparatedByString:@":"];
  607. if (components.count != 4) {
  608. return NO;
  609. }
  610. NSString *suppliedFingerprintString = components[3];
  611. if (!suppliedFingerprintString.length) {
  612. return NO;
  613. }
  614. uint64_t suppliedFingerprint;
  615. NSScanner *scanner = [NSScanner scannerWithString:suppliedFingerprintString];
  616. if (![scanner scanHexLongLong:&suppliedFingerprint]) {
  617. return NO;
  618. }
  619. if ([version isEqual:@"1:"]) {
  620. // The v1 hash algorithm is not permitted on the client so the actual hash cannot be validated.
  621. return YES;
  622. }
  623. // Unknown version.
  624. return NO;
  625. }
  626. - (NSString *)expectedBundleID {
  627. return _options.bundleID;
  628. }
  629. // end App ID validation
  630. #pragma mark - Reading From Plist & User Defaults
  631. /**
  632. * Clears the data collection switch from the standard NSUserDefaults for easier testing and
  633. * readability.
  634. */
  635. - (void)clearDataCollectionSwitchFromUserDefaults {
  636. NSString *key =
  637. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, self.name];
  638. [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
  639. }
  640. /**
  641. * Reads the data collection switch from the standard NSUserDefaults for easier testing and
  642. * readability.
  643. */
  644. + (nullable NSNumber *)readDataCollectionSwitchFromUserDefaultsForApp:(FIRApp *)app {
  645. // Read the object in user defaults, and only return if it's an NSNumber.
  646. NSString *key =
  647. [NSString stringWithFormat:kFIRGlobalAppDataCollectionEnabledDefaultsKeyFormat, app.name];
  648. id collectionEnabledDefaultsObject = [[NSUserDefaults standardUserDefaults] objectForKey:key];
  649. if ([collectionEnabledDefaultsObject isKindOfClass:[NSNumber class]]) {
  650. return collectionEnabledDefaultsObject;
  651. }
  652. return nil;
  653. }
  654. /**
  655. * Reads the data collection switch from the Info.plist for easier testing and readability. Will
  656. * only read once from the plist and return the cached value.
  657. */
  658. + (nullable NSNumber *)readDataCollectionSwitchFromPlist {
  659. static NSNumber *collectionEnabledPlistObject;
  660. static dispatch_once_t onceToken;
  661. dispatch_once(&onceToken, ^{
  662. // Read the data from the `Info.plist`, only assign it if it's there and an NSNumber.
  663. id plistValue = [[NSBundle mainBundle]
  664. objectForInfoDictionaryKey:kFIRGlobalAppDataCollectionEnabledPlistKey];
  665. if (plistValue && [plistValue isKindOfClass:[NSNumber class]]) {
  666. collectionEnabledPlistObject = (NSNumber *)plistValue;
  667. }
  668. });
  669. return collectionEnabledPlistObject;
  670. }
  671. #pragma mark - Sending Logs
  672. - (void)sendLogsWithServiceName:(NSString *)serviceName
  673. version:(NSString *)version
  674. error:(NSError *)error {
  675. // If the user has manually turned off data collection, return and don't send logs.
  676. if (![self isDataCollectionDefaultEnabled]) {
  677. return;
  678. }
  679. NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:@{
  680. kFIRAppDiagnosticsConfigurationTypeKey : @(FIRConfigTypeSDK),
  681. kFIRAppDiagnosticsSDKNameKey : serviceName,
  682. kFIRAppDiagnosticsSDKVersionKey : version,
  683. kFIRAppDiagnosticsFIRAppKey : self
  684. }];
  685. if (error) {
  686. userInfo[kFIRAppDiagnosticsErrorKey] = error;
  687. }
  688. [[NSNotificationCenter defaultCenter] postNotificationName:kFIRAppDiagnosticsNotification
  689. object:nil
  690. userInfo:userInfo];
  691. }
  692. @end