FIRCoreDiagnostics.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <objc/runtime.h>
  17. #include <sys/utsname.h>
  18. #import "GoogleDataTransport/GDTCORLibrary/Internal/GoogleDataTransportInternal.h"
  19. #import "GoogleUtilities/Environment/Private/GULAppEnvironmentUtil.h"
  20. #import "GoogleUtilities/Environment/Private/GULHeartbeatDateStorage.h"
  21. #import "GoogleUtilities/Logger/Private/GULLogger.h"
  22. #import "Interop/CoreDiagnostics/Public/FIRCoreDiagnosticsData.h"
  23. #import "Interop/CoreDiagnostics/Public/FIRCoreDiagnosticsInterop.h"
  24. #import <nanopb/pb.h>
  25. #import <nanopb/pb_decode.h>
  26. #import <nanopb/pb_encode.h>
  27. #import "Firebase/CoreDiagnostics/FIRCDLibrary/Protogen/nanopb/firebasecore.nanopb.h"
  28. /** The logger service string to use when printing to the console. */
  29. static GULLoggerService kFIRCoreDiagnostics = @"[FirebaseCoreDiagnostics/FIRCoreDiagnostics]";
  30. #ifdef FIREBASE_BUILD_ZIP_FILE
  31. static BOOL kUsingZipFile = YES;
  32. #else // FIREBASE_BUILD_ZIP_FILE
  33. static BOOL kUsingZipFile = NO;
  34. #endif // FIREBASE_BUILD_ZIP_FILE
  35. #if SWIFT_PACKAGE
  36. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_SPM
  37. #elif FIREBASE_BUILD_CARTHAGE
  38. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_CARTHAGE
  39. #elif FIREBASE_BUILD_ZIP_FILE
  40. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_ZIP_FILE
  41. #else
  42. #define kDeploymentType logs_proto_mobilesdk_ios_ICoreConfiguration_DeploymentType_COCOAPODS
  43. #endif
  44. static NSString *const kFIRServiceMLModelInterpreter = @"MLModelInterpreter";
  45. static NSString *const kFIRServiceAdMob = @"AdMob";
  46. static NSString *const kFIRServiceAuth = @"Auth";
  47. static NSString *const kFIRServiceAuthUI = @"AuthUI";
  48. static NSString *const kFIRServiceCrash = @"Crash";
  49. static NSString *const kFIRServiceDatabase = @"Database";
  50. static NSString *const kFIRServiceDynamicLinks = @"DynamicLinks";
  51. static NSString *const kFIRServiceFirestore = @"Firestore";
  52. static NSString *const kFIRServiceFunctions = @"Functions";
  53. static NSString *const kFIRServiceIAM = @"InAppMessaging";
  54. static NSString *const kFIRServiceInstanceID = @"InstanceID";
  55. static NSString *const kFIRServiceInvites = @"Invites";
  56. static NSString *const kFIRServiceMessaging = @"Messaging";
  57. static NSString *const kFIRServiceMeasurement = @"Measurement";
  58. static NSString *const kFIRServicePerformance = @"Performance";
  59. static NSString *const kFIRServiceRemoteConfig = @"RemoteConfig";
  60. static NSString *const kFIRServiceStorage = @"Storage";
  61. static NSString *const kGGLServiceAnalytics = @"Analytics";
  62. static NSString *const kGGLServiceSignIn = @"SignIn";
  63. static NSString *const kFIRAppDiagnosticsConfigurationTypeKey =
  64. @"FIRAppDiagnosticsConfigurationTypeKey";
  65. static NSString *const kFIRAppDiagnosticsFIRAppKey = @"FIRAppDiagnosticsFIRAppKey";
  66. static NSString *const kFIRAppDiagnosticsSDKNameKey = @"FIRAppDiagnosticsSDKNameKey";
  67. static NSString *const kFIRAppDiagnosticsSDKVersionKey = @"FIRAppDiagnosticsSDKVersionKey";
  68. static NSString *const kFIRCoreDiagnosticsHeartbeatTag = @"FIRCoreDiagnostics";
  69. /**
  70. * The file name to the recent heartbeat date.
  71. */
  72. NSString *const kFIRCoreDiagnosticsHeartbeatDateFileName = @"FIREBASE_DIAGNOSTICS_HEARTBEAT_DATE";
  73. /**
  74. * @note This should implement the GDTCOREventDataObject protocol, but can't because of
  75. * weak-linking.
  76. */
  77. @interface FIRCoreDiagnosticsLog : NSObject
  78. /** The config that will be converted to proto bytes. */
  79. @property(nonatomic) logs_proto_mobilesdk_ios_ICoreConfiguration config;
  80. @end
  81. @implementation FIRCoreDiagnosticsLog
  82. - (instancetype)initWithConfig:(logs_proto_mobilesdk_ios_ICoreConfiguration)config {
  83. self = [super init];
  84. if (self) {
  85. _config = config;
  86. }
  87. return self;
  88. }
  89. // Provided and required by the GDTCOREventDataObject protocol.
  90. - (NSData *)transportBytes {
  91. pb_ostream_t sizestream = PB_OSTREAM_SIZING;
  92. // Encode 1 time to determine the size.
  93. if (!pb_encode(&sizestream, logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config)) {
  94. GDTCORLogError(GDTCORMCETransportBytesError, @"Error in nanopb encoding for size: %s",
  95. PB_GET_ERROR(&sizestream));
  96. }
  97. // Encode a 2nd time to actually get the bytes from it.
  98. size_t bufferSize = sizestream.bytes_written;
  99. CFMutableDataRef dataRef = CFDataCreateMutable(CFAllocatorGetDefault(), bufferSize);
  100. CFDataSetLength(dataRef, bufferSize);
  101. pb_ostream_t ostream = pb_ostream_from_buffer((void *)CFDataGetBytePtr(dataRef), bufferSize);
  102. if (!pb_encode(&ostream, logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config)) {
  103. GDTCORLogError(GDTCORMCETransportBytesError, @"Error in nanopb encoding for bytes: %s",
  104. PB_GET_ERROR(&ostream));
  105. }
  106. CFDataSetLength(dataRef, ostream.bytes_written);
  107. return CFBridgingRelease(dataRef);
  108. }
  109. - (void)dealloc {
  110. pb_release(logs_proto_mobilesdk_ios_ICoreConfiguration_fields, &_config);
  111. }
  112. @end
  113. NS_ASSUME_NONNULL_BEGIN
  114. /** This class produces a protobuf containing diagnostics and usage data to be logged. */
  115. @interface FIRCoreDiagnostics : NSObject <FIRCoreDiagnosticsInterop>
  116. /** The queue on which all diagnostics collection will occur. */
  117. @property(nonatomic, readonly) dispatch_queue_t diagnosticsQueue;
  118. /** The transport object used to send data. */
  119. @property(nonatomic, readonly) GDTCORTransport *transport;
  120. /** The storage to store the date of the last sent heartbeat. */
  121. @property(nonatomic, readonly) GULHeartbeatDateStorage *heartbeatDateStorage;
  122. @end
  123. NS_ASSUME_NONNULL_END
  124. @implementation FIRCoreDiagnostics
  125. + (instancetype)sharedInstance {
  126. static FIRCoreDiagnostics *sharedInstance;
  127. static dispatch_once_t onceToken;
  128. dispatch_once(&onceToken, ^{
  129. sharedInstance = [[FIRCoreDiagnostics alloc] init];
  130. });
  131. return sharedInstance;
  132. }
  133. - (instancetype)init {
  134. GDTCORTransport *transport = [[GDTCORTransport alloc] initWithMappingID:@"137"
  135. transformers:nil
  136. target:kGDTCORTargetFLL];
  137. GULHeartbeatDateStorage *dateStorage =
  138. [[GULHeartbeatDateStorage alloc] initWithFileName:kFIRCoreDiagnosticsHeartbeatDateFileName];
  139. return [self initWithTransport:transport heartbeatDateStorage:dateStorage];
  140. }
  141. /** Initializer for unit tests.
  142. *
  143. * @param transport A `GDTCORTransport` instance which that be used to send event.
  144. * @param heartbeatDateStorage An instanse of date storage to track heartbeat sending.
  145. * @return Returns the initialized `FIRCoreDiagnostics` instance.
  146. */
  147. - (instancetype)initWithTransport:(GDTCORTransport *)transport
  148. heartbeatDateStorage:(GULHeartbeatDateStorage *)heartbeatDateStorage {
  149. self = [super init];
  150. if (self) {
  151. _diagnosticsQueue =
  152. dispatch_queue_create("com.google.FIRCoreDiagnostics", DISPATCH_QUEUE_SERIAL);
  153. _transport = transport;
  154. _heartbeatDateStorage = heartbeatDateStorage;
  155. }
  156. return self;
  157. }
  158. #pragma mark - Metadata helpers
  159. /** Returns the model of iOS device. Sample platform strings are @"iPhone7,1" for iPhone 6 Plus,
  160. * @"iPhone7,2" for iPhone 6, etc. Refer to the Hardware strings at
  161. * https://en.wikipedia.org/wiki/List_of_iOS_devices
  162. *
  163. * @return The device model as an NSString.
  164. */
  165. + (NSString *)deviceModel {
  166. static NSString *deviceModel = nil;
  167. if (deviceModel == nil) {
  168. struct utsname systemInfo;
  169. uname(&systemInfo);
  170. deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  171. }
  172. return deviceModel;
  173. }
  174. #pragma mark - nanopb helper functions
  175. /** Callocs a pb_bytes_array and copies the given NSString's bytes into the bytes array.
  176. *
  177. * @note Memory needs to be free manually, through pb_free or pb_release.
  178. * @param string The string to encode as pb_bytes.
  179. */
  180. pb_bytes_array_t *FIREncodeString(NSString *string) {
  181. NSData *stringBytes = [string dataUsingEncoding:NSUTF8StringEncoding];
  182. return FIREncodeData(stringBytes);
  183. }
  184. /** Callocs a pb_bytes_array and copies the given NSData bytes into the bytes array.
  185. *
  186. * @note Memory needs to be free manually, through pb_free or pb_release.
  187. * @param data The data to copy into the new bytes array.
  188. */
  189. pb_bytes_array_t *FIREncodeData(NSData *data) {
  190. pb_bytes_array_t *pbBytesArray = calloc(1, PB_BYTES_ARRAY_T_ALLOCSIZE(data.length));
  191. if (pbBytesArray != NULL) {
  192. [data getBytes:pbBytesArray->bytes length:data.length];
  193. pbBytesArray->size = (pb_size_t)data.length;
  194. }
  195. return pbBytesArray;
  196. }
  197. /** Maps a service string to the representative nanopb enum.
  198. *
  199. * @param serviceString The SDK service string to convert.
  200. * @return The representative nanopb enum.
  201. */
  202. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType FIRMapFromServiceStringToTypeEnum(
  203. NSString *serviceString) {
  204. static NSDictionary<NSString *, NSNumber *> *serviceStringToTypeEnum;
  205. if (serviceStringToTypeEnum == nil) {
  206. serviceStringToTypeEnum = @{
  207. kFIRServiceAdMob : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ADMOB),
  208. kFIRServiceMessaging : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_MESSAGING),
  209. kFIRServiceMeasurement :
  210. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_MEASUREMENT),
  211. kFIRServiceRemoteConfig :
  212. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_REMOTE_CONFIG),
  213. kFIRServiceDatabase : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_DATABASE),
  214. kFIRServiceDynamicLinks :
  215. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_DYNAMIC_LINKS),
  216. kFIRServiceAuth : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_AUTH),
  217. kFIRServiceAuthUI : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_AUTH_UI),
  218. kFIRServiceFirestore : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_FIRESTORE),
  219. kFIRServiceFunctions : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_FUNCTIONS),
  220. kFIRServicePerformance :
  221. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_PERFORMANCE),
  222. kFIRServiceStorage : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_STORAGE),
  223. kFIRServiceMLModelInterpreter :
  224. @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ML_MODEL_INTERPRETER),
  225. kGGLServiceAnalytics : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ANALYTICS),
  226. kGGLServiceSignIn : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_SIGN_IN),
  227. kFIRServiceIAM : @(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_IN_APP_MESSAGING),
  228. };
  229. }
  230. if (serviceStringToTypeEnum[serviceString] != nil) {
  231. return (int32_t)serviceStringToTypeEnum[serviceString].longLongValue;
  232. }
  233. return logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_UNKNOWN_SDK_SERVICE;
  234. }
  235. #pragma mark - Proto population functions
  236. /** Populates the given proto with data related to an SDK logDiagnostics call from the
  237. * diagnosticObjects dictionary.
  238. *
  239. * @param config The proto to populate
  240. * @param diagnosticObjects The dictionary of diagnostics objects.
  241. */
  242. void FIRPopulateProtoWithInfoFromUserInfoParams(logs_proto_mobilesdk_ios_ICoreConfiguration *config,
  243. NSDictionary<NSString *, id> *diagnosticObjects) {
  244. NSNumber *configurationType = diagnosticObjects[kFIRCDConfigurationTypeKey];
  245. if (configurationType != nil) {
  246. switch (configurationType.integerValue) {
  247. case logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_CORE:
  248. config->configuration_type =
  249. logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_CORE;
  250. config->has_configuration_type = 1;
  251. break;
  252. case logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_SDK:
  253. config->configuration_type =
  254. logs_proto_mobilesdk_ios_ICoreConfiguration_ConfigurationType_SDK;
  255. config->has_configuration_type = 1;
  256. break;
  257. default:
  258. break;
  259. }
  260. }
  261. NSString *sdkName = diagnosticObjects[kFIRCDSdkNameKey];
  262. if (sdkName) {
  263. config->sdk_name = FIRMapFromServiceStringToTypeEnum(sdkName);
  264. config->has_sdk_name = 1;
  265. }
  266. NSString *version = diagnosticObjects[kFIRCDSdkVersionKey];
  267. if (version) {
  268. config->sdk_version = FIREncodeString(version);
  269. }
  270. }
  271. /** Populates the given proto with data from the calling FIRApp using the given
  272. * diagnosticObjects dictionary.
  273. *
  274. * @param config The proto to populate
  275. * @param diagnosticObjects The dictionary of diagnostics objects.
  276. */
  277. void FIRPopulateProtoWithCommonInfoFromApp(logs_proto_mobilesdk_ios_ICoreConfiguration *config,
  278. NSDictionary<NSString *, id> *diagnosticObjects) {
  279. config->pod_name = logs_proto_mobilesdk_ios_ICoreConfiguration_PodName_FIREBASE;
  280. config->has_pod_name = 1;
  281. if (!diagnosticObjects[kFIRCDllAppsCountKey]) {
  282. GDTCORLogError(GDTCORMCEGeneralError, @"%@",
  283. @"App count is a required value in the data dict.");
  284. }
  285. config->app_count = (int32_t)[diagnosticObjects[kFIRCDllAppsCountKey] integerValue];
  286. config->has_app_count = 1;
  287. NSString *googleAppID = diagnosticObjects[kFIRCDGoogleAppIDKey];
  288. if (googleAppID.length) {
  289. config->app_id = FIREncodeString(googleAppID);
  290. }
  291. NSString *bundleID = diagnosticObjects[kFIRCDBundleIDKey];
  292. if (bundleID.length) {
  293. config->bundle_id = FIREncodeString(bundleID);
  294. }
  295. NSString *firebaseUserAgent = diagnosticObjects[kFIRCDFirebaseUserAgentKey];
  296. if (firebaseUserAgent.length) {
  297. config->platform_info = FIREncodeString(firebaseUserAgent);
  298. }
  299. NSNumber *usingOptionsFromDefaultPlist = diagnosticObjects[kFIRCDUsingOptionsFromDefaultPlistKey];
  300. if (usingOptionsFromDefaultPlist != nil) {
  301. config->use_default_app = [usingOptionsFromDefaultPlist boolValue];
  302. config->has_use_default_app = 1;
  303. }
  304. NSString *libraryVersionID = diagnosticObjects[kFIRCDLibraryVersionIDKey];
  305. if (libraryVersionID) {
  306. config->icore_version = FIREncodeString(libraryVersionID);
  307. }
  308. NSString *deviceModel = [FIRCoreDiagnostics deviceModel];
  309. if (deviceModel.length) {
  310. config->device_model = FIREncodeString(deviceModel);
  311. }
  312. NSString *osVersion = [GULAppEnvironmentUtil systemVersion];
  313. if (osVersion.length) {
  314. config->os_version = FIREncodeString(osVersion);
  315. }
  316. config->using_zip_file = kUsingZipFile;
  317. config->has_using_zip_file = 1;
  318. config->deployment_type = kDeploymentType;
  319. config->has_deployment_type = 1;
  320. config->deployed_in_app_store = [GULAppEnvironmentUtil isFromAppStore];
  321. config->has_deployed_in_app_store = 1;
  322. }
  323. /** Populates the given proto with installed services data.
  324. *
  325. * @param config The proto to populate
  326. */
  327. void FIRPopulateProtoWithInstalledServices(logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  328. NSMutableArray<NSNumber *> *sdkServiceInstalledArray = [NSMutableArray array];
  329. // AdMob
  330. if (NSClassFromString(@"GADBannerView") != nil) {
  331. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAdMob))];
  332. }
  333. // CloudMessaging
  334. if (NSClassFromString(@"FIRMessaging") != nil) {
  335. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMessaging))];
  336. }
  337. // RemoteConfig
  338. if (NSClassFromString(@"FIRRemoteConfig") != nil) {
  339. [sdkServiceInstalledArray
  340. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceRemoteConfig))];
  341. }
  342. // Measurement/Analtyics
  343. if (NSClassFromString(@"FIRAnalytics") != nil) {
  344. [sdkServiceInstalledArray
  345. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMeasurement))];
  346. }
  347. // ML Model Interpreter
  348. if (NSClassFromString(@"FIRCustomModelInterpreter") != nil) {
  349. [sdkServiceInstalledArray
  350. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceMLModelInterpreter))];
  351. }
  352. // Database
  353. if (NSClassFromString(@"FIRDatabase") != nil) {
  354. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceDatabase))];
  355. }
  356. // DynamicDeepLink
  357. if (NSClassFromString(@"FIRDynamicLinks") != nil) {
  358. [sdkServiceInstalledArray
  359. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceDynamicLinks))];
  360. }
  361. // Auth
  362. if (NSClassFromString(@"FIRAuth") != nil) {
  363. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAuth))];
  364. }
  365. // AuthUI
  366. if (NSClassFromString(@"FUIAuth") != nil) {
  367. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceAuthUI))];
  368. }
  369. // Firestore
  370. if (NSClassFromString(@"FIRFirestore") != nil) {
  371. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceFirestore))];
  372. }
  373. // Functions
  374. if (NSClassFromString(@"FIRFunctions") != nil) {
  375. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceFunctions))];
  376. }
  377. // Performance
  378. if (NSClassFromString(@"FIRPerformance") != nil) {
  379. [sdkServiceInstalledArray
  380. addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServicePerformance))];
  381. }
  382. // Storage
  383. if (NSClassFromString(@"FIRStorage") != nil) {
  384. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceStorage))];
  385. }
  386. // SignIn via Google pod
  387. if (NSClassFromString(@"GIDSignIn") != nil && NSClassFromString(@"GGLContext") != nil) {
  388. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kGGLServiceSignIn))];
  389. }
  390. // Analytics via Google pod
  391. if (NSClassFromString(@"GAI") != nil && NSClassFromString(@"GGLContext") != nil) {
  392. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kGGLServiceAnalytics))];
  393. }
  394. // In-App Messaging
  395. if (NSClassFromString(@"FIRInAppMessaging") != nil) {
  396. [sdkServiceInstalledArray addObject:@(FIRMapFromServiceStringToTypeEnum(kFIRServiceIAM))];
  397. }
  398. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType *servicesInstalled =
  399. calloc(sdkServiceInstalledArray.count,
  400. sizeof(logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType));
  401. if (servicesInstalled == NULL) {
  402. return;
  403. }
  404. for (NSUInteger i = 0; i < sdkServiceInstalledArray.count; i++) {
  405. NSNumber *typeEnum = sdkServiceInstalledArray[i];
  406. logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType serviceType =
  407. (int32_t)typeEnum.integerValue;
  408. servicesInstalled[i] = serviceType;
  409. }
  410. config->sdk_service_installed = servicesInstalled;
  411. config->sdk_service_installed_count = (int32_t)sdkServiceInstalledArray.count;
  412. }
  413. /** Populates the proto with the number of linked frameworks.
  414. *
  415. * @param config The proto to populate.
  416. */
  417. void FIRPopulateProtoWithNumberOfLinkedFrameworks(
  418. logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  419. int numFrameworks = -1; // Subtract the app binary itself.
  420. unsigned int numImages;
  421. const char **imageNames = objc_copyImageNames(&numImages);
  422. for (unsigned int i = 0; i < numImages; i++) {
  423. NSString *imageName = [NSString stringWithUTF8String:imageNames[i]];
  424. if ([imageName rangeOfString:@"System/Library"].length != 0 // Apple .frameworks
  425. || [imageName rangeOfString:@"Developer/Library"].length != 0 // Xcode debug .frameworks
  426. || [imageName rangeOfString:@"usr/lib"].length != 0) { // Public .dylibs
  427. continue;
  428. }
  429. numFrameworks++;
  430. }
  431. free(imageNames);
  432. config->dynamic_framework_count = numFrameworks;
  433. config->has_dynamic_framework_count = 1;
  434. }
  435. /** Populates the proto with Info.plist values.
  436. *
  437. * @param config The proto to populate.
  438. */
  439. void FIRPopulateProtoWithInfoPlistValues(logs_proto_mobilesdk_ios_ICoreConfiguration *config) {
  440. NSDictionary<NSString *, id> *info = [[NSBundle mainBundle] infoDictionary];
  441. NSString *xcodeVersion = info[@"DTXcodeBuild"] ?: @"";
  442. NSString *sdkVersion = info[@"DTSDKBuild"] ?: @"";
  443. NSString *combinedVersions = [NSString stringWithFormat:@"%@-%@", xcodeVersion, sdkVersion];
  444. config->apple_framework_version = FIREncodeString(combinedVersions);
  445. NSString *minVersion = info[@"MinimumOSVersion"];
  446. if (minVersion) {
  447. config->min_supported_ios_version = FIREncodeString(minVersion);
  448. }
  449. // Apps can turn off swizzling in the Info.plist, check if they've explicitly set the value and
  450. // report it. It's enabled by default.
  451. NSNumber *appDelegateSwizzledNum = info[@"FirebaseAppDelegateProxyEnabled"];
  452. BOOL appDelegateSwizzled = YES;
  453. if ([appDelegateSwizzledNum isKindOfClass:[NSNumber class]]) {
  454. appDelegateSwizzled = [appDelegateSwizzledNum boolValue];
  455. }
  456. config->swizzling_enabled = appDelegateSwizzled;
  457. config->has_swizzling_enabled = 1;
  458. }
  459. #pragma mark - FIRCoreDiagnosticsInterop
  460. + (void)sendDiagnosticsData:(nonnull id<FIRCoreDiagnosticsData>)diagnosticsData {
  461. FIRCoreDiagnostics *diagnostics = [FIRCoreDiagnostics sharedInstance];
  462. [diagnostics sendDiagnosticsData:diagnosticsData];
  463. }
  464. - (void)sendDiagnosticsData:(nonnull id<FIRCoreDiagnosticsData>)diagnosticsData {
  465. dispatch_async(self.diagnosticsQueue, ^{
  466. NSDictionary<NSString *, id> *diagnosticObjects = diagnosticsData.diagnosticObjects;
  467. NSNumber *isDataCollectionDefaultEnabled =
  468. diagnosticObjects[kFIRCDIsDataCollectionDefaultEnabledKey];
  469. if (isDataCollectionDefaultEnabled && ![isDataCollectionDefaultEnabled boolValue]) {
  470. return;
  471. }
  472. // Create the proto.
  473. logs_proto_mobilesdk_ios_ICoreConfiguration icore_config =
  474. logs_proto_mobilesdk_ios_ICoreConfiguration_init_default;
  475. icore_config.using_gdt = 1;
  476. icore_config.has_using_gdt = 1;
  477. // Populate the proto with information.
  478. FIRPopulateProtoWithInfoFromUserInfoParams(&icore_config, diagnosticObjects);
  479. FIRPopulateProtoWithCommonInfoFromApp(&icore_config, diagnosticObjects);
  480. FIRPopulateProtoWithInstalledServices(&icore_config);
  481. FIRPopulateProtoWithNumberOfLinkedFrameworks(&icore_config);
  482. FIRPopulateProtoWithInfoPlistValues(&icore_config);
  483. [self setHeartbeatFlagIfNeededToConfig:&icore_config];
  484. // This log object is capable of converting the proto to bytes.
  485. FIRCoreDiagnosticsLog *log = [[FIRCoreDiagnosticsLog alloc] initWithConfig:icore_config];
  486. // Send the log as a telemetry event.
  487. GDTCOREvent *event = [self.transport eventForTransport];
  488. event.dataObject = (id<GDTCOREventDataObject>)log;
  489. [self.transport sendTelemetryEvent:event];
  490. });
  491. }
  492. #pragma mark - Heartbeat
  493. - (void)setHeartbeatFlagIfNeededToConfig:(logs_proto_mobilesdk_ios_ICoreConfiguration *)config {
  494. // Check if need to send a heartbeat.
  495. NSDate *currentDate = [NSDate date];
  496. NSDate *lastCheckin =
  497. [self.heartbeatDateStorage heartbeatDateForTag:kFIRCoreDiagnosticsHeartbeatTag];
  498. if (lastCheckin) {
  499. // Ensure the previous checkin was on a different date in the past.
  500. if ([self isDate:currentDate inSameDayOrBeforeThan:lastCheckin]) {
  501. return;
  502. }
  503. }
  504. // Update heartbeat sent date.
  505. [self.heartbeatDateStorage setHearbeatDate:currentDate forTag:kFIRCoreDiagnosticsHeartbeatTag];
  506. // Set the flag.
  507. config->sdk_name = logs_proto_mobilesdk_ios_ICoreConfiguration_ServiceType_ICORE;
  508. config->has_sdk_name = 1;
  509. }
  510. - (BOOL)isDate:(NSDate *)date1 inSameDayOrBeforeThan:(NSDate *)date2 {
  511. return [[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2] ||
  512. [date1 compare:date2] == NSOrderedAscending;
  513. }
  514. @end