SessionDelegate.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. /// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features.
  26. open class SessionDelegate: NSObject {
  27. private let fileManager: FileManager
  28. weak var stateProvider: SessionStateProvider?
  29. var eventMonitor: EventMonitor?
  30. /// Creates an instance from the given `FileManager`.
  31. ///
  32. /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files.
  33. /// `.default` by default.
  34. public init(fileManager: FileManager = .default) {
  35. self.fileManager = fileManager
  36. }
  37. /// Internal method to find and cast requests while maintaining some integrity checking.
  38. ///
  39. /// - Parameters:
  40. /// - task: The `URLSessionTask` for which to find the associated `Request`.
  41. /// - type: The `Request` subclass type to cast any `Request` associate with `task`.
  42. func request<R: Request>(for task: URLSessionTask, as type: R.Type) -> R? {
  43. guard let provider = stateProvider else {
  44. assertionFailure("StateProvider is nil.")
  45. return nil
  46. }
  47. return provider.request(for: task) as? R
  48. }
  49. }
  50. /// Type which provides various `Session` state values.
  51. protocol SessionStateProvider: AnyObject {
  52. var serverTrustManager: ServerTrustManager? { get }
  53. var redirectHandler: RedirectHandler? { get }
  54. var cachedResponseHandler: CachedResponseHandler? { get }
  55. func request(for task: URLSessionTask) -> Request?
  56. func didGatherMetricsForTask(_ task: URLSessionTask)
  57. func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void)
  58. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
  59. func cancelRequestsForSessionInvalidation(with error: Error?)
  60. }
  61. // MARK: URLSessionDelegate
  62. extension SessionDelegate: URLSessionDelegate {
  63. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  64. eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
  65. stateProvider?.cancelRequestsForSessionInvalidation(with: error)
  66. }
  67. }
  68. // MARK: URLSessionTaskDelegate
  69. extension SessionDelegate: URLSessionTaskDelegate {
  70. /// Result of a `URLAuthenticationChallenge` evaluation.
  71. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?)
  72. open func urlSession(_ session: URLSession,
  73. task: URLSessionTask,
  74. didReceive challenge: URLAuthenticationChallenge,
  75. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  76. eventMonitor?.urlSession(session, task: task, didReceive: challenge)
  77. let evaluation: ChallengeEvaluation
  78. switch challenge.protectionSpace.authenticationMethod {
  79. case NSURLAuthenticationMethodServerTrust:
  80. evaluation = attemptServerTrustAuthentication(with: challenge)
  81. case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM,
  82. NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate:
  83. evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
  84. default:
  85. evaluation = (.performDefaultHandling, nil, nil)
  86. }
  87. if let error = evaluation.error {
  88. stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
  89. }
  90. completionHandler(evaluation.disposition, evaluation.credential)
  91. }
  92. /// Evaluates the server trust `URLAuthenticationChallenge` received.
  93. ///
  94. /// - Parameter challenge: The `URLAuthenticationChallenge`.
  95. ///
  96. /// - Returns: The `ChallengeEvaluation`.
  97. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  98. let host = challenge.protectionSpace.host
  99. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  100. let trust = challenge.protectionSpace.serverTrust
  101. else {
  102. return (.performDefaultHandling, nil, nil)
  103. }
  104. do {
  105. guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
  106. return (.performDefaultHandling, nil, nil)
  107. }
  108. try evaluator.evaluate(trust, forHost: host)
  109. return (.useCredential, URLCredential(trust: trust), nil)
  110. } catch {
  111. return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error))))
  112. }
  113. }
  114. /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`.
  115. ///
  116. /// - Parameters:
  117. /// - challenge: The `URLAuthenticationChallenge`.
  118. /// - task: The `URLSessionTask` which received the challenge.
  119. ///
  120. /// - Returns: The `ChallengeEvaluation`.
  121. func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge,
  122. belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  123. guard challenge.previousFailureCount == 0 else {
  124. return (.rejectProtectionSpace, nil, nil)
  125. }
  126. guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
  127. return (.performDefaultHandling, nil, nil)
  128. }
  129. return (.useCredential, credential, nil)
  130. }
  131. open func urlSession(_ session: URLSession,
  132. task: URLSessionTask,
  133. didSendBodyData bytesSent: Int64,
  134. totalBytesSent: Int64,
  135. totalBytesExpectedToSend: Int64) {
  136. eventMonitor?.urlSession(session,
  137. task: task,
  138. didSendBodyData: bytesSent,
  139. totalBytesSent: totalBytesSent,
  140. totalBytesExpectedToSend: totalBytesExpectedToSend)
  141. stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
  142. totalBytesExpectedToSend: totalBytesExpectedToSend)
  143. }
  144. open func urlSession(_ session: URLSession,
  145. task: URLSessionTask,
  146. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  147. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  148. guard let request = request(for: task, as: UploadRequest.self) else {
  149. assertionFailure("needNewBodyStream did not find UploadRequest.")
  150. completionHandler(nil)
  151. return
  152. }
  153. completionHandler(request.inputStream())
  154. }
  155. open func urlSession(_ session: URLSession,
  156. task: URLSessionTask,
  157. willPerformHTTPRedirection response: HTTPURLResponse,
  158. newRequest request: URLRequest,
  159. completionHandler: @escaping (URLRequest?) -> Void) {
  160. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  161. if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
  162. redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
  163. } else {
  164. completionHandler(request)
  165. }
  166. }
  167. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  168. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  169. stateProvider?.request(for: task)?.didGatherMetrics(metrics)
  170. stateProvider?.didGatherMetricsForTask(task)
  171. }
  172. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  173. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  174. let request = stateProvider?.request(for: task)
  175. stateProvider?.didCompleteTask(task) {
  176. request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) })
  177. }
  178. }
  179. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  180. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  181. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  182. }
  183. }
  184. // MARK: URLSessionDataDelegate
  185. extension SessionDelegate: URLSessionDataDelegate {
  186. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  187. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  188. if let request = request(for: dataTask, as: DataRequest.self) {
  189. request.didReceive(data: data)
  190. } else if let request = request(for: dataTask, as: DataStreamRequest.self) {
  191. request.didReceive(data: data)
  192. } else {
  193. assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive")
  194. return
  195. }
  196. }
  197. open func urlSession(_ session: URLSession,
  198. dataTask: URLSessionDataTask,
  199. willCacheResponse proposedResponse: CachedURLResponse,
  200. completionHandler: @escaping (CachedURLResponse?) -> Void) {
  201. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  202. if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
  203. handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
  204. } else {
  205. completionHandler(proposedResponse)
  206. }
  207. }
  208. }
  209. // MARK: URLSessionDownloadDelegate
  210. extension SessionDelegate: URLSessionDownloadDelegate {
  211. open func urlSession(_ session: URLSession,
  212. downloadTask: URLSessionDownloadTask,
  213. didResumeAtOffset fileOffset: Int64,
  214. expectedTotalBytes: Int64) {
  215. eventMonitor?.urlSession(session,
  216. downloadTask: downloadTask,
  217. didResumeAtOffset: fileOffset,
  218. expectedTotalBytes: expectedTotalBytes)
  219. guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
  220. assertionFailure("downloadTask did not find DownloadRequest.")
  221. return
  222. }
  223. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  224. totalBytesExpectedToWrite: expectedTotalBytes)
  225. }
  226. open func urlSession(_ session: URLSession,
  227. downloadTask: URLSessionDownloadTask,
  228. didWriteData bytesWritten: Int64,
  229. totalBytesWritten: Int64,
  230. totalBytesExpectedToWrite: Int64) {
  231. eventMonitor?.urlSession(session,
  232. downloadTask: downloadTask,
  233. didWriteData: bytesWritten,
  234. totalBytesWritten: totalBytesWritten,
  235. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  236. guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
  237. assertionFailure("downloadTask did not find DownloadRequest.")
  238. return
  239. }
  240. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  241. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  242. }
  243. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  244. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  245. guard let request = request(for: downloadTask, as: DownloadRequest.self) else {
  246. assertionFailure("downloadTask did not find DownloadRequest.")
  247. return
  248. }
  249. let (destination, options): (URL, DownloadRequest.Options)
  250. if let response = request.response {
  251. (destination, options) = request.destination(location, response)
  252. } else {
  253. // If there's no response this is likely a local file download, so generate the temporary URL directly.
  254. (destination, options) = (DownloadRequest.defaultDestinationURL(location), [])
  255. }
  256. eventMonitor?.request(request, didCreateDestinationURL: destination)
  257. do {
  258. if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
  259. try fileManager.removeItem(at: destination)
  260. }
  261. if options.contains(.createIntermediateDirectories) {
  262. let directory = destination.deletingLastPathComponent()
  263. try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
  264. }
  265. try fileManager.moveItem(at: location, to: destination)
  266. request.didFinishDownloading(using: downloadTask, with: .success(destination))
  267. } catch {
  268. request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error,
  269. source: location,
  270. destination: destination)))
  271. }
  272. }
  273. }