FIRMessagingUtilities.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright 2017 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 "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  17. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  18. #import <GoogleUtilities/GULUserDefaults.h>
  19. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  21. static const uint64_t kBytesToMegabytesDivisor = 1024 * 1024LL;
  22. NSString *const kFIRMessagingInstanceIDUserDefaultsKeyLocale =
  23. @"com.firebase.instanceid.user_defaults.locale"; // locale key stored in GULUserDefaults
  24. static NSString *const kFIRMessagingAPNSSandboxPrefix = @"s_";
  25. static NSString *const kFIRMessagingAPNSProdPrefix = @"p_";
  26. static NSString *const kFIRMessagingWatchKitExtensionPoint = @"com.apple.watchkit";
  27. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  28. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  29. #else
  30. static NSString *const kEntitlementsAPSEnvironmentKey =
  31. @"Entitlements.com.apple.developer.aps-environment";
  32. #endif
  33. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  34. #pragma mark - URL Helpers
  35. NSString *FIRMessagingTokenRegisterServer() {
  36. return @"https://fcmtoken.googleapis.com/register";
  37. }
  38. #pragma mark - Time
  39. int64_t FIRMessagingCurrentTimestampInSeconds(void) {
  40. return (int64_t)[[NSDate date] timeIntervalSince1970];
  41. }
  42. int64_t FIRMessagingCurrentTimestampInMilliseconds(void) {
  43. return (int64_t)(FIRMessagingCurrentTimestampInSeconds() * 1000.0);
  44. }
  45. #pragma mark - App Info
  46. NSString *FIRMessagingCurrentAppVersion(void) {
  47. NSString *version = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
  48. if (![version length]) {
  49. FIRMessagingLoggerError(kFIRMessagingMessageCodeUtilities000,
  50. @"Could not find current app version");
  51. return @"";
  52. }
  53. return version;
  54. }
  55. NSString *FIRMessagingBundleIDByRemovingLastPartFrom(NSString *bundleID) {
  56. NSString *bundleIDComponentsSeparator = @".";
  57. NSMutableArray<NSString *> *bundleIDComponents =
  58. [[bundleID componentsSeparatedByString:bundleIDComponentsSeparator] mutableCopy];
  59. [bundleIDComponents removeLastObject];
  60. return [bundleIDComponents componentsJoinedByString:bundleIDComponentsSeparator];
  61. }
  62. NSString *FIRMessagingAppIdentifier(void) {
  63. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  64. #if TARGET_OS_WATCH
  65. if (FIRMessagingIsWatchKitExtension()) {
  66. // The code is running in watchKit extension target but the actually bundleID is in the watchKit
  67. // target. So we need to remove the last part of the bundle ID in watchKit extension to match
  68. // the one in watchKit target.
  69. return FIRMessagingBundleIDByRemovingLastPartFrom(bundleID);
  70. } else {
  71. return bundleID;
  72. }
  73. #else
  74. return bundleID;
  75. #endif
  76. }
  77. NSString *FIRMessagingFirebaseAppID() {
  78. return [FIROptions defaultOptions].googleAppID;
  79. }
  80. BOOL FIRMessagingIsWatchKitExtension(void) {
  81. #if TARGET_OS_WATCH
  82. NSDictionary<NSString *, id> *infoDict = [[NSBundle mainBundle] infoDictionary];
  83. NSDictionary<NSString *, id> *extensionAttrDict = infoDict[@"NSExtension"];
  84. if (!extensionAttrDict) {
  85. return NO;
  86. }
  87. NSString *extensionPointId = extensionAttrDict[@"NSExtensionPointIdentifier"];
  88. if (extensionPointId) {
  89. return [extensionPointId isEqualToString:kFIRMessagingWatchKitExtensionPoint];
  90. } else {
  91. return NO;
  92. }
  93. #else
  94. return NO;
  95. #endif
  96. }
  97. uint64_t FIRMessagingGetFreeDiskSpaceInMB(void) {
  98. NSError *error;
  99. NSArray *paths =
  100. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  101. NSDictionary *attributesMap =
  102. [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject]
  103. error:&error];
  104. if (attributesMap) {
  105. uint64_t totalSizeInBytes __unused = [attributesMap[NSFileSystemSize] longLongValue];
  106. uint64_t freeSizeInBytes = [attributesMap[NSFileSystemFreeSize] longLongValue];
  107. FIRMessagingLoggerDebug(
  108. kFIRMessagingMessageCodeUtilities001, @"Device has capacity %llu MB with %llu MB free.",
  109. totalSizeInBytes / kBytesToMegabytesDivisor, freeSizeInBytes / kBytesToMegabytesDivisor);
  110. return ((double)freeSizeInBytes) / kBytesToMegabytesDivisor;
  111. } else {
  112. FIRMessagingLoggerError(kFIRMessagingMessageCodeUtilities002,
  113. @"Error in retreiving device's free memory %@", error);
  114. return 0;
  115. }
  116. }
  117. NSSearchPathDirectory FIRMessagingSupportedDirectory(void) {
  118. #if TARGET_OS_TV
  119. return NSCachesDirectory;
  120. #else
  121. return NSApplicationSupportDirectory;
  122. #endif
  123. }
  124. #pragma mark - Locales
  125. NSDictionary *FIRMessagingFirebaselocalesMap(void) {
  126. return @{
  127. // Albanian
  128. @"sq" : @[ @"sq_AL" ],
  129. // Belarusian
  130. @"be" : @[ @"be_BY" ],
  131. // Bulgarian
  132. @"bg" : @[ @"bg_BG" ],
  133. // Catalan
  134. @"ca" : @[ @"ca", @"ca_ES" ],
  135. // Croatian
  136. @"hr" : @[ @"hr", @"hr_HR" ],
  137. // Czech
  138. @"cs" : @[ @"cs", @"cs_CZ" ],
  139. // Danish
  140. @"da" : @[ @"da", @"da_DK" ],
  141. // Estonian
  142. @"et" : @[ @"et_EE" ],
  143. // Finnish
  144. @"fi" : @[ @"fi", @"fi_FI" ],
  145. // Hebrew
  146. @"he" : @[ @"he", @"iw_IL" ],
  147. // Hindi
  148. @"hi" : @[ @"hi_IN" ],
  149. // Hungarian
  150. @"hu" : @[ @"hu", @"hu_HU" ],
  151. // Icelandic
  152. @"is" : @[ @"is_IS" ],
  153. // Indonesian
  154. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  155. // Irish
  156. @"ga" : @[ @"ga_IE" ],
  157. // Korean
  158. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  159. // Latvian
  160. @"lv" : @[ @"lv_LV" ],
  161. // Lithuanian
  162. @"lt" : @[ @"lt_LT" ],
  163. // Macedonian
  164. @"mk" : @[ @"mk_MK" ],
  165. // Malay
  166. @"ms" : @[ @"ms_MY" ],
  167. // Maltese
  168. @"mt" : @[ @"mt_MT" ],
  169. // Polish
  170. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  171. // Romanian
  172. @"ro" : @[ @"ro", @"ro_RO" ],
  173. // Russian
  174. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  175. // Slovak
  176. @"sk" : @[ @"sk", @"sk_SK" ],
  177. // Slovenian
  178. @"sl" : @[ @"sl_SI" ],
  179. // Swedish
  180. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  181. // Turkish
  182. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  183. // Ukrainian
  184. @"uk" : @[ @"uk", @"uk_UA" ],
  185. // Vietnamese
  186. @"vi" : @[ @"vi", @"vi_VN" ],
  187. // The following are groups of locales or locales that sub-divide a
  188. // language).
  189. // Arabic
  190. @"ar" : @[
  191. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  192. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  193. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  194. ],
  195. // Simplified Chinese
  196. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  197. // Traditional Chinese
  198. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  199. // Dutch
  200. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  201. // English
  202. @"en" : @[
  203. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  204. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  205. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  206. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  207. ],
  208. // French
  209. @"fr" :
  210. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  211. // German
  212. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  213. // Greek
  214. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  215. // Italian
  216. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  217. // Japanese
  218. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  219. // Norwegian
  220. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  221. // Brazilian Portuguese
  222. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  223. // European Portuguese
  224. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  225. // Serbian
  226. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  227. // European Spanish
  228. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  229. // Mexican Spanish
  230. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  231. // Latin American Spanish
  232. @"es_419" : @[
  233. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  234. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  235. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  236. ],
  237. // Thai
  238. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  239. };
  240. }
  241. NSArray *FIRMessagingFirebaseLocales(void) {
  242. NSMutableArray *locales = [NSMutableArray array];
  243. NSDictionary *localesMap = FIRMessagingFirebaselocalesMap();
  244. for (NSString *key in localesMap) {
  245. [locales addObjectsFromArray:localesMap[key]];
  246. }
  247. return locales;
  248. }
  249. NSString *FIRMessagingCurrentLocale() {
  250. NSArray *locales = FIRMessagingFirebaseLocales();
  251. NSArray *preferredLocalizations =
  252. [NSBundle preferredLocalizationsFromArray:locales
  253. forPreferences:[NSLocale preferredLanguages]];
  254. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  255. // Use en as the default language
  256. return legalDocsLanguage ? legalDocsLanguage : @"en";
  257. }
  258. BOOL FIRMessagingHasLocaleChanged() {
  259. NSString *lastLocale = [[GULUserDefaults standardUserDefaults]
  260. stringForKey:kFIRMessagingInstanceIDUserDefaultsKeyLocale];
  261. NSString *currentLocale = FIRMessagingCurrentLocale();
  262. if (lastLocale) {
  263. if ([currentLocale isEqualToString:lastLocale]) {
  264. return NO;
  265. }
  266. }
  267. return YES;
  268. }
  269. NSString *FIRMessagingStringForAPNSDeviceToken(NSData *deviceToken) {
  270. NSMutableString *APNSToken = [NSMutableString string];
  271. unsigned char *bytes = (unsigned char *)[deviceToken bytes];
  272. for (int i = 0; i < (int)deviceToken.length; i++) {
  273. [APNSToken appendFormat:@"%02x", bytes[i]];
  274. }
  275. return APNSToken;
  276. }
  277. NSString *FIRMessagingAPNSTupleStringForTokenAndServerType(NSData *deviceToken, BOOL isSandbox) {
  278. if (deviceToken == nil) {
  279. // A nil deviceToken leads to an invalid tuple string, so return nil.
  280. return nil;
  281. }
  282. NSString *prefix = isSandbox ? kFIRMessagingAPNSSandboxPrefix : kFIRMessagingAPNSProdPrefix;
  283. NSString *APNSString = FIRMessagingStringForAPNSDeviceToken(deviceToken);
  284. NSString *APNSTupleString = [NSString stringWithFormat:@"%@%@", prefix, APNSString];
  285. return APNSTupleString;
  286. }
  287. BOOL FIRMessagingIsProductionApp(void) {
  288. const BOOL defaultAppTypeProd = YES;
  289. NSError *error = nil;
  290. if ([GULAppEnvironmentUtil isSimulator]) {
  291. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  292. @"Running InstanceID on a simulator doesn't have APNS. "
  293. @"Use prod profile by default.");
  294. return defaultAppTypeProd;
  295. }
  296. if ([GULAppEnvironmentUtil isFromAppStore]) {
  297. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  298. return defaultAppTypeProd;
  299. }
  300. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  301. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  302. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  303. #elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  304. NSString *path = [[[NSBundle mainBundle] bundlePath]
  305. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  306. #endif
  307. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  308. // Distributed via TestFlight
  309. return defaultAppTypeProd;
  310. }
  311. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  312. if (!profileData.length || error) {
  313. NSString *errorString =
  314. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  315. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  316. return defaultAppTypeProd;
  317. }
  318. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  319. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  320. // ASCII. Replace any 0s or invalid characters in the input.
  321. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  322. for (int i = 0; i < profileData.length; i++) {
  323. uint8_t currentByte = profileBytes[i];
  324. if (!currentByte || currentByte > 127) {
  325. profileBytes[i] = '.';
  326. }
  327. }
  328. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  329. length:profileData.length
  330. encoding:NSASCIIStringEncoding
  331. freeWhenDone:NO];
  332. if (error || !embeddedProfile.length) {
  333. NSString *errorString =
  334. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  335. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  336. return defaultAppTypeProd;
  337. }
  338. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  339. NSString *plistContents;
  340. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  341. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  342. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  343. }
  344. }
  345. if (!plistContents.length) {
  346. return defaultAppTypeProd;
  347. }
  348. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  349. if (!data.length) {
  350. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  351. @"Couldn't read plist fetched from embedded mobileprovision");
  352. return defaultAppTypeProd;
  353. }
  354. NSError *plistMapError;
  355. id plistData = [NSPropertyListSerialization propertyListWithData:data
  356. options:NSPropertyListImmutable
  357. format:nil
  358. error:&plistMapError];
  359. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  360. NSString *errorString =
  361. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  362. plistMapError.localizedDescription];
  363. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014, @"%@", errorString);
  364. return defaultAppTypeProd;
  365. }
  366. NSDictionary *plistMap = (NSDictionary *)plistData;
  367. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  368. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInstanceID012,
  369. @"Provisioning profile has specifically provisioned devices, "
  370. @"most likely a Dev profile.");
  371. }
  372. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  373. NSString *debugString __unused =
  374. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  375. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInstanceID013, @"%@", debugString);
  376. // No aps-environment in the profile.
  377. if (!apsEnvironment.length) {
  378. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID014,
  379. @"No aps-environment set. If testing on a device APNS is not "
  380. @"correctly configured. Please recheck your provisioning "
  381. @"profiles. If testing on a simulator this is fine since APNS "
  382. @"doesn't work on the simulator.");
  383. return defaultAppTypeProd;
  384. }
  385. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  386. return NO;
  387. }
  388. return defaultAppTypeProd;
  389. }
  390. BOOL FIRMessagingIsSandboxApp(void) {
  391. static BOOL isSandboxApp = YES;
  392. static dispatch_once_t onceToken;
  393. dispatch_once(&onceToken, ^{
  394. isSandboxApp = !FIRMessagingIsProductionApp();
  395. });
  396. return isSandboxApp;
  397. }