FIRNetworkURLSession.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. #import "Private/FIRNetworkURLSession.h"
  15. #import "Private/FIRMutableDictionary.h"
  16. #import "Private/FIRNetworkConstants.h"
  17. #import "Private/FIRNetworkMessageCode.h"
  18. #import "Private/FIRLogger.h"
  19. @implementation FIRNetworkURLSession {
  20. /// The handler to be called when the request completes or error has occurs.
  21. FIRNetworkURLSessionCompletionHandler _completionHandler;
  22. /// Session ID generated randomly with a fixed prefix.
  23. NSString *_sessionID;
  24. /// The session configuration.
  25. NSURLSessionConfiguration *_sessionConfig;
  26. /// The path to the directory where all temporary files are stored before uploading.
  27. NSURL *_networkDirectoryURL;
  28. /// The downloaded data from fetching.
  29. NSData *_downloadedData;
  30. /// The path to the temporary file which stores the uploading data.
  31. NSURL *_uploadingFileURL;
  32. /// The current request.
  33. NSURLRequest *_request;
  34. }
  35. #pragma mark - Init
  36. - (instancetype)initWithNetworkLoggerDelegate:(id<FIRNetworkLoggerDelegate>)networkLoggerDelegate {
  37. self = [super init];
  38. if (self) {
  39. // Create URL to the directory where all temporary files to upload have to be stored.
  40. NSArray *paths =
  41. NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  42. NSString *applicationSupportDirectory = paths.firstObject;
  43. NSArray *tempPathComponents = @[
  44. applicationSupportDirectory,
  45. kFIRNetworkApplicationSupportSubdirectory,
  46. kFIRNetworkTempDirectoryName
  47. ];
  48. _networkDirectoryURL = [NSURL fileURLWithPathComponents:tempPathComponents];
  49. _sessionID = [NSString stringWithFormat:@"%@-%@", kFIRNetworkBackgroundSessionConfigIDPrefix,
  50. [[NSUUID UUID] UUIDString]];
  51. _loggerDelegate = networkLoggerDelegate;
  52. }
  53. return self;
  54. }
  55. #pragma mark - External Methods
  56. #pragma mark - To be called from AppDelegate
  57. + (void)handleEventsForBackgroundURLSessionID:(NSString *)sessionID
  58. completionHandler:
  59. (FIRNetworkSystemCompletionHandler)systemCompletionHandler {
  60. // The session may not be FIRAnalytics background. Ignore those that do not have the prefix.
  61. if (![sessionID hasPrefix:kFIRNetworkBackgroundSessionConfigIDPrefix]) {
  62. return;
  63. }
  64. FIRNetworkURLSession *fetcher = [self fetcherWithSessionIdentifier:sessionID];
  65. if (fetcher != nil) {
  66. [fetcher addSystemCompletionHandler:systemCompletionHandler forSession:sessionID];
  67. } else {
  68. FIRLogError(kFIRLoggerCore,
  69. [NSString stringWithFormat:@"I-NET%06ld", (long)kFIRNetworkMessageCodeNetwork003],
  70. @"Failed to retrieve background session with ID %@ after app is relaunched.",
  71. sessionID);
  72. }
  73. }
  74. #pragma mark - External Methods
  75. /// Sends an async POST request using NSURLSession for iOS >= 7.0, and returns an ID of the
  76. /// connection.
  77. - (NSString *)sessionIDFromAsyncPOSTRequest:(NSURLRequest *)request
  78. completionHandler:(FIRNetworkURLSessionCompletionHandler)handler {
  79. // NSURLSessionUploadTask does not work with NSData in the background.
  80. // To avoid this issue, write the data to a temporary file to upload it.
  81. // Make a temporary file with the data subset.
  82. _uploadingFileURL = [self temporaryFilePathWithSessionID:_sessionID];
  83. NSError *writeError;
  84. NSURLSessionUploadTask *postRequestTask;
  85. NSURLSession *session;
  86. BOOL didWriteFile = NO;
  87. // Clean up the entire temp folder to avoid temp files that remain in case the previous session
  88. // crashed and did not clean up.
  89. [self maybeRemoveTempFilesAtURL:_networkDirectoryURL
  90. expiringTime:kFIRNetworkTempFolderExpireTime];
  91. // If there is no background network enabled, no need to write to file. This will allow default
  92. // network session which runs on the foreground.
  93. if (_backgroundNetworkEnabled && [self ensureTemporaryDirectoryExists]) {
  94. didWriteFile = [request.HTTPBody writeToFile:_uploadingFileURL.path
  95. options:NSDataWritingAtomic
  96. error:&writeError];
  97. if (writeError) {
  98. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  99. messageCode:kFIRNetworkMessageCodeURLSession000
  100. message:@"Failed to write request data to file"
  101. context:writeError];
  102. }
  103. }
  104. if (didWriteFile) {
  105. // Exclude this file from backing up to iTunes. There are conflicting reports that excluding
  106. // directory from backing up does not excluding files of that directory from backing up.
  107. [self excludeFromBackupForURL:_uploadingFileURL];
  108. _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID];
  109. [self populateSessionConfig:_sessionConfig withRequest:request];
  110. session = [NSURLSession sessionWithConfiguration:_sessionConfig
  111. delegate:self
  112. delegateQueue:[NSOperationQueue mainQueue]];
  113. postRequestTask = [session uploadTaskWithRequest:request fromFile:_uploadingFileURL];
  114. } else {
  115. // If we cannot write to file, just send it in the foreground.
  116. _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  117. [self populateSessionConfig:_sessionConfig withRequest:request];
  118. _sessionConfig.URLCache = nil;
  119. session = [NSURLSession sessionWithConfiguration:_sessionConfig
  120. delegate:self
  121. delegateQueue:[NSOperationQueue mainQueue]];
  122. postRequestTask = [session uploadTaskWithRequest:request fromData:request.HTTPBody];
  123. }
  124. if (!session || !postRequestTask) {
  125. NSError *error =
  126. [[NSError alloc] initWithDomain:kFIRNetworkErrorDomain
  127. code:FIRErrorCodeNetworkRequestCreation
  128. userInfo:@{
  129. kFIRNetworkErrorContext : @"Cannot create network session"
  130. }];
  131. [self callCompletionHandler:handler withResponse:nil data:nil error:error];
  132. return nil;
  133. }
  134. // Save the session into memory.
  135. NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIDToFetcherMap];
  136. [sessionIdentifierToFetcherMap setObject:self forKey:_sessionID];
  137. _request = [request copy];
  138. // Store completion handler because background session does not accept handler block but custom
  139. // delegate.
  140. _completionHandler = [handler copy];
  141. [postRequestTask resume];
  142. return _sessionID;
  143. }
  144. /// Sends an async GET request using NSURLSession for iOS >= 7.0, and returns an ID of the session.
  145. - (NSString *)sessionIDFromAsyncGETRequest:(NSURLRequest *)request
  146. completionHandler:(FIRNetworkURLSessionCompletionHandler)handler {
  147. if (_backgroundNetworkEnabled) {
  148. _sessionConfig = [self backgroundSessionConfigWithSessionID:_sessionID];
  149. } else {
  150. _sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  151. }
  152. [self populateSessionConfig:_sessionConfig withRequest:request];
  153. // Do not cache the GET request.
  154. _sessionConfig.URLCache = nil;
  155. NSURLSession *session = [NSURLSession sessionWithConfiguration:_sessionConfig
  156. delegate:self
  157. delegateQueue:[NSOperationQueue mainQueue]];
  158. NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
  159. if (!session || !downloadTask) {
  160. NSError *error =
  161. [[NSError alloc] initWithDomain:kFIRNetworkErrorDomain
  162. code:FIRErrorCodeNetworkRequestCreation
  163. userInfo:@{
  164. kFIRNetworkErrorContext : @"Cannot create network session"
  165. }];
  166. [self callCompletionHandler:handler withResponse:nil data:nil error:error];
  167. return nil;
  168. }
  169. // Save the session into memory.
  170. NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIDToFetcherMap];
  171. [sessionIdentifierToFetcherMap setObject:self forKey:_sessionID];
  172. _request = [request copy];
  173. _completionHandler = [handler copy];
  174. [downloadTask resume];
  175. return _sessionID;
  176. }
  177. #pragma mark - NSURLSessionTaskDelegate
  178. /// Called by the NSURLSession once the download task is completed. The file is saved in the
  179. /// provided URL so we need to read the data and store into _downloadedData. Once the session is
  180. /// completed, URLSession:task:didCompleteWithError will be called and the completion handler will
  181. /// be called with the downloaded data.
  182. - (void)URLSession:(NSURLSession *)session
  183. downloadTask:(NSURLSessionDownloadTask *)task
  184. didFinishDownloadingToURL:(NSURL *)url {
  185. if (!url.path) {
  186. [_loggerDelegate
  187. firNetwork_logWithLevel:kFIRNetworkLogLevelError
  188. messageCode:kFIRNetworkMessageCodeURLSession001
  189. message:@"Unable to read downloaded data from empty temp path"];
  190. _downloadedData = nil;
  191. return;
  192. }
  193. NSError *error;
  194. _downloadedData = [NSData dataWithContentsOfFile:url.path options:0 error:&error];
  195. if (error) {
  196. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  197. messageCode:kFIRNetworkMessageCodeURLSession002
  198. message:@"Cannot read the content of downloaded data"
  199. context:error];
  200. _downloadedData = nil;
  201. }
  202. }
  203. - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
  204. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelDebug
  205. messageCode:kFIRNetworkMessageCodeURLSession003
  206. message:@"Background session finished"
  207. context:session.configuration.identifier];
  208. [self callSystemCompletionHandler:session.configuration.identifier];
  209. }
  210. - (void)URLSession:(NSURLSession *)session
  211. task:(NSURLSessionTask *)task
  212. didCompleteWithError:(NSError *)error {
  213. // Avoid any chance of recursive behavior leading to it being used repeatedly.
  214. FIRNetworkURLSessionCompletionHandler handler = _completionHandler;
  215. _completionHandler = nil;
  216. if (task.response) {
  217. // The following assertion should always be true for HTTP requests, see https://goo.gl/gVLxT7.
  218. NSAssert([task.response isKindOfClass:[NSHTTPURLResponse class]], @"URL response must be HTTP");
  219. // The server responded so ignore the error created by the system.
  220. error = nil;
  221. } else if (!error) {
  222. error =
  223. [[NSError alloc] initWithDomain:kFIRNetworkErrorDomain
  224. code:FIRErrorCodeNetworkInvalidResponse
  225. userInfo:@{
  226. kFIRNetworkErrorContext : @"Network Error: Empty network response"
  227. }];
  228. }
  229. [self callCompletionHandler:handler
  230. withResponse:(NSHTTPURLResponse *)task.response
  231. data:_downloadedData
  232. error:error];
  233. // Remove the temp file to avoid trashing devices with lots of temp files.
  234. [self removeTempItemAtURL:_uploadingFileURL];
  235. // Try to clean up stale files again.
  236. [self maybeRemoveTempFilesAtURL:_networkDirectoryURL
  237. expiringTime:kFIRNetworkTempFolderExpireTime];
  238. }
  239. - (void)URLSession:(NSURLSession *)session
  240. task:(NSURLSessionTask *)task
  241. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  242. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
  243. NSURLCredential *credential))completionHandler {
  244. // The handling is modeled after GTMSessionFetcher.
  245. if ([challenge.protectionSpace.authenticationMethod
  246. isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  247. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
  248. if (serverTrust == NULL) {
  249. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelDebug
  250. messageCode:kFIRNetworkMessageCodeURLSession004
  251. message:@"Received empty server trust for host. Host"
  252. context:_request.URL];
  253. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  254. return;
  255. }
  256. NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
  257. if (!credential) {
  258. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelWarning
  259. messageCode:kFIRNetworkMessageCodeURLSession005
  260. message:@"Unable to verify server identity. Host"
  261. context:_request.URL];
  262. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  263. return;
  264. }
  265. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelDebug
  266. messageCode:kFIRNetworkMessageCodeURLSession006
  267. message:@"Received SSL challenge for host. Host"
  268. context:_request.URL];
  269. void (^callback)(BOOL) = ^(BOOL allow) {
  270. if (allow) {
  271. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  272. } else {
  273. [_loggerDelegate
  274. firNetwork_logWithLevel:kFIRNetworkLogLevelDebug
  275. messageCode:kFIRNetworkMessageCodeURLSession007
  276. message:@"Cancelling authentication challenge for host. Host"
  277. context:_request.URL];
  278. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  279. }
  280. };
  281. // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7.
  282. CFRetain(serverTrust);
  283. // Evaluate the certificate chain.
  284. //
  285. // The delegate queue may be the main thread. Trust evaluation could cause some
  286. // blocking network activity, so we must evaluate async, as documented at
  287. // https://developer.apple.com/library/ios/technotes/tn2232/
  288. dispatch_queue_t evaluateBackgroundQueue =
  289. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  290. dispatch_async(evaluateBackgroundQueue, ^{
  291. SecTrustResultType trustEval = kSecTrustResultInvalid;
  292. BOOL shouldAllow;
  293. OSStatus trustError;
  294. @synchronized([FIRNetworkURLSession class]) {
  295. trustError = SecTrustEvaluate(serverTrust, &trustEval);
  296. }
  297. if (trustError != errSecSuccess) {
  298. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  299. messageCode:kFIRNetworkMessageCodeURLSession008
  300. message:@"Cannot evaluate server trust. Error, host"
  301. contexts:@[ @(trustError), _request.URL ]];
  302. shouldAllow = NO;
  303. } else {
  304. // Having a trust level "unspecified" by the user is the usual result, described at
  305. // https://developer.apple.com/library/mac/qa/qa1360
  306. shouldAllow =
  307. (trustEval == kSecTrustResultUnspecified || trustEval == kSecTrustResultProceed);
  308. }
  309. // Call the call back with the permission.
  310. callback(shouldAllow);
  311. CFRelease(serverTrust);
  312. });
  313. return;
  314. }
  315. // Default handling for other Auth Challenges.
  316. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  317. }
  318. #pragma mark - Internal Methods
  319. /// Stores system completion handler with session ID as key.
  320. - (void)addSystemCompletionHandler:(FIRNetworkSystemCompletionHandler)handler
  321. forSession:(NSString *)identifier {
  322. if (!handler) {
  323. [_loggerDelegate
  324. firNetwork_logWithLevel:kFIRNetworkLogLevelError
  325. messageCode:kFIRNetworkMessageCodeURLSession009
  326. message:@"Cannot store nil system completion handler in network"];
  327. return;
  328. }
  329. if (!identifier.length) {
  330. [_loggerDelegate
  331. firNetwork_logWithLevel:kFIRNetworkLogLevelError
  332. messageCode:kFIRNetworkMessageCodeURLSession010
  333. message:@"Cannot store system completion handler with empty network "
  334. "session identifier"];
  335. return;
  336. }
  337. FIRMutableDictionary *systemCompletionHandlers =
  338. [[self class] sessionIDToSystemCompletionHandlerDictionary];
  339. if (systemCompletionHandlers[identifier]) {
  340. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelWarning
  341. messageCode:kFIRNetworkMessageCodeURLSession011
  342. message:@"Got multiple system handlers for a single session ID"
  343. context:identifier];
  344. }
  345. systemCompletionHandlers[identifier] = handler;
  346. }
  347. /// Calls the system provided completion handler with the session ID stored in the dictionary.
  348. /// The handler will be removed from the dictionary after being called.
  349. - (void)callSystemCompletionHandler:(NSString *)identifier {
  350. FIRMutableDictionary *systemCompletionHandlers =
  351. [[self class] sessionIDToSystemCompletionHandlerDictionary];
  352. FIRNetworkSystemCompletionHandler handler = [systemCompletionHandlers objectForKey:identifier];
  353. if (handler) {
  354. [systemCompletionHandlers removeObjectForKey:identifier];
  355. dispatch_async(dispatch_get_main_queue(), ^{
  356. handler();
  357. });
  358. }
  359. }
  360. /// Sets or updates the session ID of this session.
  361. - (void)setSessionID:(NSString *)sessionID {
  362. _sessionID = [sessionID copy];
  363. }
  364. /// Creates a background session configuration with the session ID using the supported method.
  365. - (NSURLSessionConfiguration *)backgroundSessionConfigWithSessionID:(NSString *)sessionID {
  366. #if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && \
  367. MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) || \
  368. (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && \
  369. __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)
  370. // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name.
  371. return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID];
  372. #elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && \
  373. MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) || \
  374. (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0)
  375. // Do a runtime check to avoid a deprecation warning about using
  376. // +backgroundSessionConfiguration: on iOS 8.
  377. if ([NSURLSessionConfiguration
  378. respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) {
  379. // Running on iOS 8+/OS X 10.10+.
  380. return [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionID];
  381. } else {
  382. // Running on iOS 7/OS X 10.9.
  383. return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID];
  384. }
  385. #else
  386. // Building with an SDK earlier than iOS 8/OS X 10.10.
  387. return [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID];
  388. #endif
  389. }
  390. - (void)maybeRemoveTempFilesAtURL:(NSURL *)folderURL expiringTime:(NSTimeInterval)staleTime {
  391. if (!folderURL.absoluteString.length) {
  392. return;
  393. }
  394. NSFileManager *fileManager = [NSFileManager defaultManager];
  395. NSError *error = nil;
  396. NSArray *properties = @[ NSURLCreationDateKey ];
  397. NSArray *directoryContent =
  398. [fileManager contentsOfDirectoryAtURL:folderURL
  399. includingPropertiesForKeys:properties
  400. options:NSDirectoryEnumerationSkipsSubdirectoryDescendants
  401. error:&error];
  402. if (error && error.code != NSFileReadNoSuchFileError) {
  403. [_loggerDelegate
  404. firNetwork_logWithLevel:kFIRNetworkLogLevelDebug
  405. messageCode:kFIRNetworkMessageCodeURLSession012
  406. message:@"Cannot get files from the temporary network folder. Error"
  407. context:error];
  408. return;
  409. }
  410. if (!directoryContent.count) {
  411. return;
  412. }
  413. NSTimeInterval now = [NSDate date].timeIntervalSince1970;
  414. for (NSURL *tempFile in directoryContent) {
  415. NSDate *creationDate;
  416. BOOL getCreationDate =
  417. [tempFile getResourceValue:&creationDate forKey:NSURLCreationDateKey error:NULL];
  418. if (!getCreationDate) {
  419. continue;
  420. }
  421. NSTimeInterval creationTimeInterval = creationDate.timeIntervalSince1970;
  422. if (fabs(now - creationTimeInterval) > staleTime) {
  423. [self removeTempItemAtURL:tempFile];
  424. }
  425. }
  426. }
  427. /// Removes the temporary file written to disk for sending the request. It has to be cleaned up
  428. /// after the session is done.
  429. - (void)removeTempItemAtURL:(NSURL *)fileURL {
  430. if (!fileURL.absoluteString.length) {
  431. return;
  432. }
  433. NSFileManager *fileManager = [NSFileManager defaultManager];
  434. NSError *error = nil;
  435. if (![fileManager removeItemAtURL:fileURL error:&error] && error.code != NSFileNoSuchFileError) {
  436. [_loggerDelegate
  437. firNetwork_logWithLevel:kFIRNetworkLogLevelError
  438. messageCode:kFIRNetworkMessageCodeURLSession013
  439. message:@"Failed to remove temporary uploading data file. Error"
  440. context:error.localizedDescription];
  441. }
  442. }
  443. /// Gets the fetcher with the session ID.
  444. + (instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier {
  445. NSMapTable *sessionIdentifierToFetcherMap = [self sessionIDToFetcherMap];
  446. FIRNetworkURLSession *session = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier];
  447. if (!session && [sessionIdentifier hasPrefix:kFIRNetworkBackgroundSessionConfigIDPrefix]) {
  448. session = [[FIRNetworkURLSession alloc] initWithNetworkLoggerDelegate:nil];
  449. [session setSessionID:sessionIdentifier];
  450. [sessionIdentifierToFetcherMap setObject:session forKey:sessionIdentifier];
  451. }
  452. return session;
  453. }
  454. /// Returns a map of the fetcher by session ID. Creates a map if it is not created.
  455. + (NSMapTable *)sessionIDToFetcherMap {
  456. static NSMapTable *sessionIDToFetcherMap;
  457. static dispatch_once_t sessionMapOnceToken;
  458. dispatch_once(&sessionMapOnceToken, ^{
  459. sessionIDToFetcherMap = [NSMapTable strongToWeakObjectsMapTable];
  460. });
  461. return sessionIDToFetcherMap;
  462. }
  463. /// Returns a map of system provided completion handler by session ID. Creates a map if it is not
  464. /// created.
  465. + (FIRMutableDictionary *)sessionIDToSystemCompletionHandlerDictionary {
  466. static FIRMutableDictionary *systemCompletionHandlers;
  467. static dispatch_once_t systemCompletionHandlerOnceToken;
  468. dispatch_once(&systemCompletionHandlerOnceToken, ^{
  469. systemCompletionHandlers = [[FIRMutableDictionary alloc] init];
  470. });
  471. return systemCompletionHandlers;
  472. }
  473. - (NSURL *)temporaryFilePathWithSessionID:(NSString *)sessionID {
  474. NSString *tempName = [NSString stringWithFormat:@"FIRUpload_temp_%@", sessionID];
  475. return [_networkDirectoryURL URLByAppendingPathComponent:tempName];
  476. }
  477. /// Makes sure that the directory to store temp files exists. If not, tries to create it and returns
  478. /// YES. If there is anything wrong, returns NO.
  479. - (BOOL)ensureTemporaryDirectoryExists {
  480. NSFileManager *fileManager = [NSFileManager defaultManager];
  481. NSError *error = nil;
  482. // Create a temporary directory if it does not exist or was deleted.
  483. if ([_networkDirectoryURL checkResourceIsReachableAndReturnError:&error]) {
  484. return YES;
  485. }
  486. if (error && error.code != NSFileReadNoSuchFileError) {
  487. [_loggerDelegate
  488. firNetwork_logWithLevel:kFIRNetworkLogLevelWarning
  489. messageCode:kFIRNetworkMessageCodeURLSession014
  490. message:@"Error while trying to access Network temp folder. Error"
  491. context:error];
  492. }
  493. NSError *writeError = nil;
  494. [fileManager createDirectoryAtURL:_networkDirectoryURL
  495. withIntermediateDirectories:YES
  496. attributes:nil
  497. error:&writeError];
  498. if (writeError) {
  499. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  500. messageCode:kFIRNetworkMessageCodeURLSession015
  501. message:@"Cannot create temporary directory. Error"
  502. context:writeError];
  503. return NO;
  504. }
  505. // Set the iCloud exclusion attribute on the Documents URL.
  506. [self excludeFromBackupForURL:_networkDirectoryURL];
  507. return YES;
  508. }
  509. - (void)excludeFromBackupForURL:(NSURL *)url {
  510. if (!url.path) {
  511. return;
  512. }
  513. // Set the iCloud exclusion attribute on the Documents URL.
  514. NSError *preventBackupError = nil;
  515. [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&preventBackupError];
  516. if (preventBackupError) {
  517. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  518. messageCode:kFIRNetworkMessageCodeURLSession016
  519. message:@"Cannot exclude temporary folder from iTunes backup"];
  520. }
  521. }
  522. - (void)URLSession:(NSURLSession *)session
  523. task:(NSURLSessionTask *)task
  524. willPerformHTTPRedirection:(NSHTTPURLResponse *)response
  525. newRequest:(NSURLRequest *)request
  526. completionHandler:(void (^)(NSURLRequest *))completionHandler {
  527. NSArray *nonAllowedRedirectionCodes = @[
  528. @(kFIRNetworkHTTPStatusCodeFound),
  529. @(kFIRNetworkHTTPStatusCodeMovedPermanently),
  530. @(kFIRNetworkHTTPStatusCodeMovedTemporarily),
  531. @(kFIRNetworkHTTPStatusCodeMultipleChoices)
  532. ];
  533. // Allow those not in the non allowed list to be followed.
  534. if (![nonAllowedRedirectionCodes containsObject:@(response.statusCode)]) {
  535. completionHandler(request);
  536. return;
  537. }
  538. // Do not allow redirection if the response code is in the non-allowed list.
  539. NSURLRequest *newRequest = request;
  540. if (response) {
  541. newRequest = nil;
  542. }
  543. completionHandler(newRequest);
  544. }
  545. #pragma mark - Helper Methods
  546. - (void)callCompletionHandler:(FIRNetworkURLSessionCompletionHandler)handler
  547. withResponse:(NSHTTPURLResponse *)response
  548. data:(NSData *)data
  549. error:(NSError *)error {
  550. if (error) {
  551. [_loggerDelegate firNetwork_logWithLevel:kFIRNetworkLogLevelError
  552. messageCode:kFIRNetworkMessageCodeURLSession017
  553. message:@"Encounter network error. Code, error"
  554. contexts:@[@(error.code), error]];
  555. }
  556. if (handler) {
  557. dispatch_async(dispatch_get_main_queue(), ^{
  558. handler(response, data, _sessionID, error);
  559. });
  560. }
  561. }
  562. - (void)populateSessionConfig:(NSURLSessionConfiguration *)sessionConfig
  563. withRequest:(NSURLRequest *)request {
  564. sessionConfig.HTTPAdditionalHeaders = request.allHTTPHeaderFields;
  565. sessionConfig.timeoutIntervalForRequest = request.timeoutInterval;
  566. sessionConfig.timeoutIntervalForResource = request.timeoutInterval;
  567. sessionConfig.requestCachePolicy = request.cachePolicy;
  568. }
  569. @end