SessionDelegate.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. deinit {
  38. NSLog("*** SessionDelegate deinitialized.")
  39. }
  40. /// Internal method to find and cast requests while maintaining some integrity checking.
  41. ///
  42. /// - Parameters:
  43. /// - task: The `URLSessionTask` for which to find the associated `Request`.
  44. /// - type: The `Request` subclass type to cast any `Request` associate with `task`.
  45. func request<R: Request>(for task: URLSessionTask, as type: R.Type) -> R? {
  46. guard let provider = stateProvider else {
  47. assertionFailure("StateProvider is nil.")
  48. return nil
  49. }
  50. return provider.request(for: task) as? R
  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, completion: @escaping () -> Void)
  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 NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM,
  83. NSURLAuthenticationMethodNegotiate:
  84. evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
  85. #if !(os(Linux) || os(Windows))
  86. case NSURLAuthenticationMethodServerTrust:
  87. evaluation = attemptServerTrustAuthentication(with: challenge)
  88. case NSURLAuthenticationMethodClientCertificate:
  89. evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task)
  90. #endif
  91. default:
  92. evaluation = (.performDefaultHandling, nil, nil)
  93. }
  94. if let error = evaluation.error {
  95. stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
  96. }
  97. completionHandler(evaluation.disposition, evaluation.credential)
  98. }
  99. #if !(os(Linux) || os(Windows))
  100. /// Evaluates the server trust `URLAuthenticationChallenge` received.
  101. ///
  102. /// - Parameter challenge: The `URLAuthenticationChallenge`.
  103. ///
  104. /// - Returns: The `ChallengeEvaluation`.
  105. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  106. let host = challenge.protectionSpace.host
  107. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  108. let trust = challenge.protectionSpace.serverTrust
  109. else {
  110. return (.performDefaultHandling, nil, nil)
  111. }
  112. do {
  113. guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
  114. return (.performDefaultHandling, nil, nil)
  115. }
  116. try evaluator.evaluate(trust, forHost: host)
  117. return (.useCredential, URLCredential(trust: trust), nil)
  118. } catch {
  119. return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error))))
  120. }
  121. }
  122. #endif
  123. /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`.
  124. ///
  125. /// - Parameters:
  126. /// - challenge: The `URLAuthenticationChallenge`.
  127. /// - task: The `URLSessionTask` which received the challenge.
  128. ///
  129. /// - Returns: The `ChallengeEvaluation`.
  130. func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge,
  131. belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  132. guard challenge.previousFailureCount == 0 else {
  133. return (.rejectProtectionSpace, nil, nil)
  134. }
  135. guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
  136. return (.performDefaultHandling, nil, nil)
  137. }
  138. return (.useCredential, credential, nil)
  139. }
  140. open func urlSession(_ session: URLSession,
  141. task: URLSessionTask,
  142. didSendBodyData bytesSent: Int64,
  143. totalBytesSent: Int64,
  144. totalBytesExpectedToSend: Int64) {
  145. eventMonitor?.urlSession(session,
  146. task: task,
  147. didSendBodyData: bytesSent,
  148. totalBytesSent: totalBytesSent,
  149. totalBytesExpectedToSend: totalBytesExpectedToSend)
  150. stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
  151. totalBytesExpectedToSend: totalBytesExpectedToSend)
  152. }
  153. open func urlSession(_ session: URLSession,
  154. task: URLSessionTask,
  155. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  156. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  157. guard let request = request(for: task, as: UploadRequest.self) else {
  158. assertionFailure("needNewBodyStream did not find UploadRequest.")
  159. completionHandler(nil)
  160. return
  161. }
  162. completionHandler(request.inputStream())
  163. }
  164. open func urlSession(_ session: URLSession,
  165. task: URLSessionTask,
  166. willPerformHTTPRedirection response: HTTPURLResponse,
  167. newRequest request: URLRequest,
  168. completionHandler: @escaping (URLRequest?) -> Void) {
  169. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  170. if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
  171. redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
  172. } else {
  173. completionHandler(request)
  174. }
  175. }
  176. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  177. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  178. stateProvider?.request(for: task)?.didGatherMetrics(metrics)
  179. stateProvider?.didGatherMetricsForTask(task)
  180. }
  181. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  182. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  183. let request = stateProvider?.request(for: task)
  184. stateProvider?.didCompleteTask(task) {
  185. request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) })
  186. }
  187. }
  188. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  189. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  190. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  191. }
  192. }
  193. // MARK: URLSessionDataDelegate
  194. extension SessionDelegate: URLSessionDataDelegate {
  195. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  196. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  197. if let request = request(for: dataTask, as: DataRequest.self) {
  198. request.didReceive(data: data)
  199. } else if let request = request(for: dataTask, as: DataStreamRequest.self) {
  200. request.didReceive(data: data)
  201. } else {
  202. assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive")
  203. return
  204. }
  205. }
  206. open func urlSession(_ session: URLSession,
  207. dataTask: URLSessionDataTask,
  208. willCacheResponse proposedResponse: CachedURLResponse,
  209. completionHandler: @escaping (CachedURLResponse?) -> Void) {
  210. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  211. if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
  212. handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
  213. } else {
  214. completionHandler(proposedResponse)
  215. }
  216. }
  217. }
  218. // MARK: URLSessionDownloadDelegate
  219. extension SessionDelegate: URLSessionDownloadDelegate {
  220. open func urlSession(_ session: URLSession,
  221. downloadTask: URLSessionDownloadTask,
  222. didResumeAtOffset fileOffset: Int64,
  223. expectedTotalBytes: Int64) {
  224. eventMonitor?.urlSession(session,
  225. downloadTask: downloadTask,
  226. didResumeAtOffset: fileOffset,
  227. expectedTotalBytes: expectedTotalBytes)
  228. guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
  229. assertionFailure("downloadTask did not find DownloadRequest.")
  230. return
  231. }
  232. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  233. totalBytesExpectedToWrite: expectedTotalBytes)
  234. }
  235. open func urlSession(_ session: URLSession,
  236. downloadTask: URLSessionDownloadTask,
  237. didWriteData bytesWritten: Int64,
  238. totalBytesWritten: Int64,
  239. totalBytesExpectedToWrite: Int64) {
  240. eventMonitor?.urlSession(session,
  241. downloadTask: downloadTask,
  242. didWriteData: bytesWritten,
  243. totalBytesWritten: totalBytesWritten,
  244. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  245. guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else {
  246. assertionFailure("downloadTask did not find DownloadRequest.")
  247. return
  248. }
  249. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  250. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  251. }
  252. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  253. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  254. guard let request = request(for: downloadTask, as: DownloadRequest.self) else {
  255. assertionFailure("downloadTask did not find DownloadRequest.")
  256. return
  257. }
  258. let (destination, options): (URL, DownloadRequest.Options)
  259. if let response = request.response {
  260. (destination, options) = request.destination(location, response)
  261. } else {
  262. // If there's no response this is likely a local file download, so generate the temporary URL directly.
  263. (destination, options) = (DownloadRequest.defaultDestinationURL(location), [])
  264. }
  265. eventMonitor?.request(request, didCreateDestinationURL: destination)
  266. do {
  267. if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
  268. try fileManager.removeItem(at: destination)
  269. }
  270. if options.contains(.createIntermediateDirectories) {
  271. let directory = destination.deletingLastPathComponent()
  272. try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
  273. }
  274. try fileManager.moveItem(at: location, to: destination)
  275. request.didFinishDownloading(using: downloadTask, with: .success(destination))
  276. } catch {
  277. request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error,
  278. source: location,
  279. destination: destination)))
  280. }
  281. }
  282. }