SessionDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // SessionDelegate.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. protocol SessionStateProvider: AnyObject {
  26. var serverTrustManager: ServerTrustManager? { get }
  27. var redirectHandler: RedirectHandler? { get }
  28. var cachedResponseHandler: CachedResponseHandler? { get }
  29. func request(for task: URLSessionTask) -> Request?
  30. func didCompleteTask(_ task: URLSessionTask)
  31. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
  32. func cancelRequestsForSessionInvalidation(with error: Error?)
  33. }
  34. open class SessionDelegate: NSObject {
  35. private let fileManager: FileManager
  36. weak var stateProvider: SessionStateProvider?
  37. var eventMonitor: EventMonitor?
  38. public init(fileManager: FileManager = .default) {
  39. self.fileManager = fileManager
  40. }
  41. }
  42. extension SessionDelegate: URLSessionDelegate {
  43. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  44. eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
  45. stateProvider?.cancelRequestsForSessionInvalidation(with: error)
  46. }
  47. }
  48. extension SessionDelegate: URLSessionTaskDelegate {
  49. /// Result of a `URLAuthenticationChallenge` evaluation.
  50. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: Error?)
  51. open func urlSession(_ session: URLSession,
  52. task: URLSessionTask,
  53. didReceive challenge: URLAuthenticationChallenge,
  54. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  55. eventMonitor?.urlSession(session, task: task, didReceive: challenge)
  56. let evaluation: ChallengeEvaluation
  57. switch challenge.protectionSpace.authenticationMethod {
  58. case NSURLAuthenticationMethodServerTrust:
  59. evaluation = attemptServerTrustAuthentication(with: challenge)
  60. case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest:
  61. evaluation = attemptHTTPAuthentication(for: challenge, belongingTo: task)
  62. // case NSURLAuthenticationMethodClientCertificate:
  63. default:
  64. evaluation = (.performDefaultHandling, nil, nil)
  65. }
  66. if let error = evaluation.error {
  67. stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
  68. }
  69. completionHandler(evaluation.disposition, evaluation.credential)
  70. }
  71. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  72. let host = challenge.protectionSpace.host
  73. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  74. let trust = challenge.protectionSpace.serverTrust
  75. else {
  76. return (.performDefaultHandling, nil, nil)
  77. }
  78. do {
  79. guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
  80. return (.performDefaultHandling, nil, nil)
  81. }
  82. try evaluator.evaluate(trust, forHost: host)
  83. return (.useCredential, URLCredential(trust: trust), nil)
  84. } catch {
  85. return (.cancelAuthenticationChallenge, nil, error)
  86. }
  87. }
  88. func attemptHTTPAuthentication(for challenge: URLAuthenticationChallenge,
  89. belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  90. guard challenge.previousFailureCount == 0 else {
  91. return (.rejectProtectionSpace, nil, nil)
  92. }
  93. guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
  94. return (.performDefaultHandling, nil, nil)
  95. }
  96. return (.useCredential, credential, nil)
  97. }
  98. open func urlSession(_ session: URLSession,
  99. task: URLSessionTask,
  100. didSendBodyData bytesSent: Int64,
  101. totalBytesSent: Int64,
  102. totalBytesExpectedToSend: Int64) {
  103. eventMonitor?.urlSession(session,
  104. task: task,
  105. didSendBodyData: bytesSent,
  106. totalBytesSent: totalBytesSent,
  107. totalBytesExpectedToSend: totalBytesExpectedToSend)
  108. stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
  109. totalBytesExpectedToSend: totalBytesExpectedToSend)
  110. }
  111. open func urlSession(_ session: URLSession,
  112. task: URLSessionTask,
  113. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  114. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  115. guard let request = stateProvider?.request(for: task) as? UploadRequest else {
  116. fatalError("needNewBodyStream for request that isn't UploadRequest.")
  117. }
  118. completionHandler(request.inputStream())
  119. }
  120. open func urlSession(_ session: URLSession,
  121. task: URLSessionTask,
  122. willPerformHTTPRedirection response: HTTPURLResponse,
  123. newRequest request: URLRequest,
  124. completionHandler: @escaping (URLRequest?) -> Void) {
  125. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  126. if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
  127. redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
  128. } else {
  129. completionHandler(request)
  130. }
  131. }
  132. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  133. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  134. stateProvider?.request(for: task)?.didGatherMetrics(metrics)
  135. }
  136. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  137. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  138. stateProvider?.request(for: task)?.didCompleteTask(task, with: error)
  139. stateProvider?.didCompleteTask(task)
  140. }
  141. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  142. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  143. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  144. }
  145. }
  146. extension SessionDelegate: URLSessionDataDelegate {
  147. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  148. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  149. guard let request = stateProvider?.request(for: dataTask) as? DataRequest else {
  150. fatalError("dataTask received data for incorrect Request subclass: \(String(describing: stateProvider?.request(for: dataTask)))")
  151. }
  152. request.didReceive(data: data)
  153. }
  154. open func urlSession(_ session: URLSession,
  155. dataTask: URLSessionDataTask,
  156. willCacheResponse proposedResponse: CachedURLResponse,
  157. completionHandler: @escaping (CachedURLResponse?) -> Void) {
  158. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  159. if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
  160. handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
  161. } else {
  162. completionHandler(proposedResponse)
  163. }
  164. }
  165. }
  166. extension SessionDelegate: URLSessionDownloadDelegate {
  167. open func urlSession(_ session: URLSession,
  168. downloadTask: URLSessionDownloadTask,
  169. didResumeAtOffset fileOffset: Int64,
  170. expectedTotalBytes: Int64) {
  171. eventMonitor?.urlSession(session,
  172. downloadTask: downloadTask,
  173. didResumeAtOffset: fileOffset,
  174. expectedTotalBytes: expectedTotalBytes)
  175. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  176. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  177. }
  178. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  179. totalBytesExpectedToWrite: expectedTotalBytes)
  180. }
  181. open func urlSession(_ session: URLSession,
  182. downloadTask: URLSessionDownloadTask,
  183. didWriteData bytesWritten: Int64,
  184. totalBytesWritten: Int64,
  185. totalBytesExpectedToWrite: Int64) {
  186. eventMonitor?.urlSession(session,
  187. downloadTask: downloadTask,
  188. didWriteData: bytesWritten,
  189. totalBytesWritten: totalBytesWritten,
  190. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  191. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  192. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  193. }
  194. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  195. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  196. }
  197. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  198. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  199. guard let request = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  200. fatalError("Download finished but either no request found or request wasn't DownloadRequest")
  201. }
  202. guard let response = request.response else {
  203. fatalError("URLSessionDownloadTask finished downloading with no response.")
  204. }
  205. let (destination, options) = (request.destination ?? DownloadRequest.defaultDestination)(location, response)
  206. eventMonitor?.request(request, didCreateDestinationURL: destination)
  207. do {
  208. if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
  209. try fileManager.removeItem(at: destination)
  210. }
  211. if options.contains(.createIntermediateDirectories) {
  212. let directory = destination.deletingLastPathComponent()
  213. try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
  214. }
  215. try fileManager.moveItem(at: location, to: destination)
  216. request.didFinishDownloading(using: downloadTask, with: .success(destination))
  217. } catch {
  218. request.didFinishDownloading(using: downloadTask, with: .failure(error))
  219. }
  220. }
  221. }