FIRNetworkURLSession.m 27 KB

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