FDLUtilities.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright 2018 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 <TargetConditionals.h>
  17. #if TARGET_OS_IOS
  18. #import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
  19. #import <UIKit/UIDevice.h>
  20. #include <sys/sysctl.h>
  21. NS_ASSUME_NONNULL_BEGIN
  22. NSString *const kFIRDLParameterDeepLinkIdentifier = @"deep_link_id";
  23. NSString *const kFIRDLParameterLink = @"link";
  24. NSString *const kFIRDLParameterMinimumAppVersion = @"imv";
  25. NSString *const kFIRDLParameterSource = @"utm_source";
  26. NSString *const kFIRDLParameterMedium = @"utm_medium";
  27. NSString *const kFIRDLParameterCampaign = @"utm_campaign";
  28. NSString *const kFIRDLParameterMatchType = @"match_type";
  29. NSString *const kFIRDLParameterInviteId = @"invitation_id";
  30. NSString *const kFIRDLParameterWeakMatchEndpoint = @"invitation_weakMatchEndpoint";
  31. NSString *const kFIRDLParameterMatchMessage = @"match_message";
  32. NSString *const kFIRDLParameterRequestIPVersion = @"request_ip_version";
  33. static NSSet *FIRDLCustomDomains = nil;
  34. NSURL *FIRDLCookieRetrievalURL(NSString *urlScheme, NSString *bundleID) {
  35. static NSString *const kFDLBundleIDQueryParameterName = @"fdl_ios_bundle_id";
  36. static NSString *const kFDLURLSchemeQueryParameterName = @"fdl_ios_url_scheme";
  37. NSURLComponents *components = [[NSURLComponents alloc] init];
  38. components.scheme = @"https";
  39. components.host = @"goo.gl";
  40. components.path = @"/app/_/deeplink";
  41. NSMutableArray *queryItems = [NSMutableArray array];
  42. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFDLBundleIDQueryParameterName
  43. value:bundleID]];
  44. [queryItems addObject:[NSURLQueryItem queryItemWithName:kFDLURLSchemeQueryParameterName
  45. value:urlScheme]];
  46. [components setQueryItems:queryItems];
  47. return [components URL];
  48. }
  49. NSString *FIRDLURLQueryStringFromDictionary(NSDictionary<NSString *, NSString *> *dictionary) {
  50. NSMutableString *parameters = [NSMutableString string];
  51. NSCharacterSet *queryCharacterSet = [NSCharacterSet alphanumericCharacterSet];
  52. NSString *parameterFormatString = @"%@%@=%@";
  53. __block NSUInteger index = 0;
  54. [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull value,
  55. BOOL *_Nonnull stop) {
  56. NSString *delimiter = index++ == 0 ? @"?" : @"&";
  57. NSString *encodedValue =
  58. [value stringByAddingPercentEncodingWithAllowedCharacters:queryCharacterSet];
  59. NSString *parameter =
  60. [NSString stringWithFormat:parameterFormatString, delimiter, key, encodedValue];
  61. [parameters appendString:parameter];
  62. }];
  63. return parameters;
  64. }
  65. NSDictionary *FIRDLDictionaryFromQuery(NSString *queryString) {
  66. NSArray<NSString *> *keyValuePairs = [queryString componentsSeparatedByString:@"&"];
  67. NSMutableDictionary *queryDictionary =
  68. [NSMutableDictionary dictionaryWithCapacity:keyValuePairs.count];
  69. for (NSString *pair in keyValuePairs) {
  70. NSArray *keyValuePair = [pair componentsSeparatedByString:@"="];
  71. if (keyValuePair.count == 2) {
  72. NSString *key = keyValuePair[0];
  73. NSString *value = [keyValuePair[1] stringByRemovingPercentEncoding];
  74. [queryDictionary setObject:value forKey:key];
  75. }
  76. }
  77. return [queryDictionary copy];
  78. }
  79. NSURL *FIRDLDeepLinkURLWithInviteID(NSString *_Nullable inviteID,
  80. NSString *_Nullable deepLinkString,
  81. NSString *_Nullable utmSource,
  82. NSString *_Nullable utmMedium,
  83. NSString *_Nullable utmCampaign,
  84. BOOL isWeakLink,
  85. NSString *_Nullable weakMatchEndpoint,
  86. NSString *_Nullable minAppVersion,
  87. NSString *URLScheme,
  88. NSString *_Nullable matchMessage) {
  89. // We are unable to use NSURLComponents as NSURLQueryItem is avilable beginning in iOS 8 and
  90. // appending our query string with NSURLComponents improperly formats the query by adding
  91. // a second '?' in the query.
  92. NSMutableDictionary *queryDictionary = [NSMutableDictionary dictionary];
  93. if (inviteID != nil) {
  94. queryDictionary[kFIRDLParameterInviteId] = inviteID;
  95. }
  96. if (deepLinkString != nil) {
  97. queryDictionary[kFIRDLParameterDeepLinkIdentifier] = deepLinkString;
  98. }
  99. if (utmSource != nil) {
  100. queryDictionary[kFIRDLParameterSource] = utmSource;
  101. }
  102. if (utmMedium != nil) {
  103. queryDictionary[kFIRDLParameterMedium] = utmMedium;
  104. }
  105. if (utmCampaign != nil) {
  106. queryDictionary[kFIRDLParameterCampaign] = utmCampaign;
  107. }
  108. if (isWeakLink) {
  109. queryDictionary[kFIRDLParameterMatchType] = @"weak";
  110. } else {
  111. queryDictionary[kFIRDLParameterMatchType] = @"unique";
  112. }
  113. if (weakMatchEndpoint != nil) {
  114. queryDictionary[kFIRDLParameterWeakMatchEndpoint] = weakMatchEndpoint;
  115. }
  116. if (minAppVersion != nil) {
  117. queryDictionary[kFIRDLParameterMinimumAppVersion] = minAppVersion;
  118. }
  119. if (matchMessage != nil) {
  120. queryDictionary[kFIRDLParameterMatchMessage] = matchMessage;
  121. }
  122. NSString *scheme = [URLScheme lowercaseString];
  123. NSString *queryString = FIRDLURLQueryStringFromDictionary(queryDictionary);
  124. NSString *urlString = [NSString stringWithFormat:@"%@://google/link/%@", scheme, queryString];
  125. return [NSURL URLWithString:urlString];
  126. }
  127. BOOL FIRDLOSVersionSupported(NSString *_Nullable systemVersion, NSString *minSupportedVersion) {
  128. systemVersion = systemVersion ?: [UIDevice currentDevice].systemVersion;
  129. return [systemVersion compare:minSupportedVersion options:NSNumericSearch] != NSOrderedAscending;
  130. }
  131. NSDate *_Nullable FIRDLAppInstallationDate() {
  132. NSURL *documentsDirectoryURL =
  133. [[[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory
  134. inDomains:NSUserDomainMask] firstObject];
  135. if (!documentsDirectoryURL) {
  136. return nil;
  137. }
  138. NSDictionary<NSString *, id> *attributes =
  139. [[NSFileManager defaultManager] attributesOfItemAtPath:documentsDirectoryURL.path error:NULL];
  140. if (attributes[NSFileCreationDate] &&
  141. [attributes[NSFileCreationDate] isKindOfClass:[NSDate class]]) {
  142. return attributes[NSFileCreationDate];
  143. }
  144. return nil;
  145. }
  146. NSString *FIRDLDeviceModelName() {
  147. // this method will return string like iPad3,3
  148. // for Simulator this will be x86_64
  149. static NSString *machineString = @"";
  150. static dispatch_once_t onceToken;
  151. dispatch_once(&onceToken, ^{
  152. size_t size;
  153. // compute string size
  154. if (sysctlbyname("hw.machine", NULL, &size, NULL, 0) == 0) {
  155. // get device name
  156. char *machine = calloc(1, size);
  157. if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == 0) {
  158. machineString = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
  159. }
  160. free(machine);
  161. }
  162. });
  163. return machineString;
  164. }
  165. NSString *FIRDLDeviceLocale() {
  166. // expected return value from this method looks like: @"en-US"
  167. return [[[NSLocale currentLocale] localeIdentifier] stringByReplacingOccurrencesOfString:@"_"
  168. withString:@"-"];
  169. }
  170. NSString *FIRDLDeviceLocaleRaw() {
  171. return [[NSLocale currentLocale] localeIdentifier];
  172. }
  173. NSString *FIRDLDeviceTimezone() {
  174. NSString *timeZoneName = [[NSTimeZone localTimeZone] name];
  175. return timeZoneName;
  176. }
  177. BOOL FIRDLIsURLForAllowedCustomDomain(NSURL *URL) {
  178. if (URL) {
  179. for (NSURL *allowedCustomDomain in FIRDLCustomDomains) {
  180. // At least one custom domain host name should match at a minimum.
  181. if ([URL.absoluteString hasPrefix:allowedCustomDomain.absoluteString]) {
  182. NSString *urlWithoutDomainURIPrefix =
  183. [URL.absoluteString substringFromIndex:allowedCustomDomain.absoluteString.length];
  184. // The urlWithoutDomainURIPrefix should be starting with '/' or '?' otherwise it means the
  185. // allowed domain is not exactly matching the incoming URL domain prefix.
  186. if ([urlWithoutDomainURIPrefix hasPrefix:@"/"] ||
  187. [urlWithoutDomainURIPrefix hasPrefix:@"?"]) {
  188. // For a valid custom domain DL Suffix the urlWithoutDomainURIPrefix should have:
  189. // 1. At least one path exists OR
  190. // 2. Should have a link query param with an http/https link
  191. NSURLComponents *components =
  192. [[NSURLComponents alloc] initWithString:urlWithoutDomainURIPrefix];
  193. if (components.path && components.path.length > 1) {
  194. // Have a path exists. So valid custom domain.
  195. return true;
  196. }
  197. if (components.queryItems && components.queryItems.count > 0) {
  198. for (NSURLQueryItem *queryItem in components.queryItems) {
  199. // Checks whether we have a link query param
  200. if ([queryItem.name caseInsensitiveCompare:@"link"] == NSOrderedSame) {
  201. // Checks whether link query param value starts with http/https
  202. if (queryItem.value && ([queryItem.value hasPrefix:@"http://"] ||
  203. [queryItem.value hasPrefix:@"https://"])) {
  204. return true;
  205. }
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. return false;
  214. }
  215. /* We are validating following domains in proper format.
  216. *.page.link
  217. *.app.goo.gl
  218. *.page.link/i/
  219. *.app.goo.gl/i/
  220. */
  221. BOOL FIRDLIsAValidDLWithFDLDomain(NSURL *_Nullable URL) {
  222. BOOL matchesRegularExpression = false;
  223. NSString *urlStr = URL.absoluteString;
  224. if ([URL.host containsString:@".page.link"] || [URL.host containsString:@".app.goo.gl"]) {
  225. // Matches the *.page.link and *.app.goo.gl domains.
  226. matchesRegularExpression =
  227. ([urlStr rangeOfString:@"^https?://[a-zA-Z0-9]+((\\.app\\.goo\\.gl)|(\\.page\\.link))((\\/"
  228. @"?\\?.*link=https?.*)|(\\/[a-zA-Z0-9-_]+)((\\/?\\?.*=.*)?$|$))"
  229. options:NSRegularExpressionSearch]
  230. .location != NSNotFound);
  231. if (!matchesRegularExpression) {
  232. // Matches the *.page.link/i/ and *.app.goo.gl/i/ domains.
  233. // Checks whether the URL is of the format :
  234. // http(s)://$DOMAIN(.page.link or .app.goo.gl)/i/$ANYTHING
  235. matchesRegularExpression =
  236. ([urlStr rangeOfString:
  237. @"^https?:\\/\\/[a-zA-Z0-9]+((\\.app\\.goo\\.gl)|(\\.page\\.link))\\/i\\/.*$"
  238. options:NSRegularExpressionSearch]
  239. .location != NSNotFound);
  240. }
  241. }
  242. return matchesRegularExpression;
  243. }
  244. /*
  245. DL can be parsed if it :
  246. 1. Has http(s)://goo.gl/app* or http(s)://page.link/app* format
  247. 2. OR http(s)://$DomainPrefix.page.link or http(s)://$DomainPrefix.app.goo.gl domain with specific
  248. format
  249. 3. OR the domain is a listed custom domain
  250. */
  251. BOOL FIRDLCanParseUniversalLinkURL(NSURL *_Nullable URL) {
  252. // Handle universal links with format |https://goo.gl/app/<appcode>?<parameters>|.
  253. // Also support page.link format.
  254. BOOL isDDLWithAppcodeInPath = ([URL.host isEqual:@"goo.gl"] || [URL.host isEqual:@"page.link"]) &&
  255. [URL.path hasPrefix:@"/app"];
  256. return isDDLWithAppcodeInPath || FIRDLIsAValidDLWithFDLDomain(URL) ||
  257. FIRDLIsURLForAllowedCustomDomain(URL);
  258. }
  259. BOOL FIRDLMatchesShortLinkFormat(NSURL *URL) {
  260. // Short Durable Link URLs always have a path or it should be a custom domain.
  261. BOOL hasPathOrCustomDomain = URL.path.length > 0 || FIRDLIsURLForAllowedCustomDomain(URL);
  262. // Must be able to parse (also checks if the URL conforms to *.app.goo.gl/* or goo.gl/app/* or
  263. // *.page.link or custom domain with valid suffix)
  264. BOOL canParse = FIRDLCanParseUniversalLinkURL(URL);
  265. // Path cannot be prefixed with /link/dismiss
  266. BOOL isDismiss = [[URL.path lowercaseString] hasPrefix:@"/link/dismiss"];
  267. // Checks short link format by having only one path after domain prefix.
  268. BOOL matchesRegularExpression =
  269. ([URL.path rangeOfString:@"/[^/]+" options:NSRegularExpressionSearch].location != NSNotFound);
  270. return hasPathOrCustomDomain && !isDismiss && canParse && matchesRegularExpression;
  271. }
  272. NSString *FIRDLMatchTypeStringFromServerString(NSString *_Nullable serverMatchTypeString) {
  273. static NSDictionary *matchMap;
  274. static dispatch_once_t onceToken;
  275. dispatch_once(&onceToken, ^{
  276. matchMap = @{
  277. @"WEAK" : @"weak",
  278. @"DEFAULT" : @"default",
  279. @"UNIQUE" : @"unique",
  280. };
  281. });
  282. return matchMap[serverMatchTypeString] ?: @"none";
  283. }
  284. void FIRDLAddToAllowListForCustomDomainsArray(NSArray *_Nonnull customDomains) {
  285. // Duplicates will be weeded out when converting to a set.
  286. NSMutableArray *validCustomDomains =
  287. [[NSMutableArray alloc] initWithCapacity:customDomains.count];
  288. for (NSString *customDomainEntry in customDomains) {
  289. // We remove trailing slashes in the path if present.
  290. NSString *domainEntry =
  291. [customDomainEntry hasSuffix:@"/"]
  292. ? [customDomainEntry substringToIndex:[customDomainEntry length] - 1]
  293. : customDomainEntry;
  294. NSURL *customDomainURL = [NSURL URLWithString:domainEntry];
  295. // We require a valid scheme for each custom domain enumerated in the info.plist file.
  296. if (customDomainURL && customDomainURL.scheme) {
  297. [validCustomDomains addObject:customDomainURL];
  298. }
  299. }
  300. // Duplicates will be weeded out when converting to a set.
  301. FIRDLCustomDomains = [NSSet setWithArray:validCustomDomains];
  302. }
  303. NS_ASSUME_NONNULL_END
  304. #endif // TARGET_OS_IOS