SessionDelegate.swift 14 KB

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