SessionDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 didGatherMetricsForTask(_ task: URLSessionTask)
  31. func didCompleteTask(_ task: URLSessionTask)
  32. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential?
  33. func cancelRequestsForSessionInvalidation(with error: Error?)
  34. }
  35. open class SessionDelegate: NSObject {
  36. private let fileManager: FileManager
  37. weak var stateProvider: SessionStateProvider?
  38. var eventMonitor: EventMonitor?
  39. public init(fileManager: FileManager = .default) {
  40. self.fileManager = fileManager
  41. }
  42. }
  43. extension SessionDelegate: URLSessionDelegate {
  44. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  45. eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
  46. stateProvider?.cancelRequestsForSessionInvalidation(with: error)
  47. }
  48. }
  49. extension SessionDelegate: URLSessionTaskDelegate {
  50. /// Result of a `URLAuthenticationChallenge` evaluation.
  51. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: Error?)
  52. open func urlSession(_ session: URLSession,
  53. task: URLSessionTask,
  54. didReceive challenge: URLAuthenticationChallenge,
  55. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  56. eventMonitor?.urlSession(session, task: task, didReceive: challenge)
  57. let evaluation: ChallengeEvaluation
  58. switch challenge.protectionSpace.authenticationMethod {
  59. case NSURLAuthenticationMethodServerTrust:
  60. evaluation = attemptServerTrustAuthentication(with: challenge)
  61. case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest:
  62. evaluation = attemptHTTPAuthentication(for: challenge, belongingTo: task)
  63. // case NSURLAuthenticationMethodClientCertificate:
  64. default:
  65. evaluation = (.performDefaultHandling, nil, nil)
  66. }
  67. if let error = evaluation.error {
  68. stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error)
  69. }
  70. completionHandler(evaluation.disposition, evaluation.credential)
  71. }
  72. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  73. let host = challenge.protectionSpace.host
  74. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  75. let trust = challenge.protectionSpace.serverTrust
  76. else {
  77. return (.performDefaultHandling, nil, nil)
  78. }
  79. do {
  80. guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else {
  81. return (.performDefaultHandling, nil, nil)
  82. }
  83. try evaluator.evaluate(trust, forHost: host)
  84. return (.useCredential, URLCredential(trust: trust), nil)
  85. } catch {
  86. return (.cancelAuthenticationChallenge, nil, error)
  87. }
  88. }
  89. func attemptHTTPAuthentication(for challenge: URLAuthenticationChallenge,
  90. belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  91. guard challenge.previousFailureCount == 0 else {
  92. return (.rejectProtectionSpace, nil, nil)
  93. }
  94. guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else {
  95. return (.performDefaultHandling, nil, nil)
  96. }
  97. return (.useCredential, credential, nil)
  98. }
  99. open func urlSession(_ session: URLSession,
  100. task: URLSessionTask,
  101. didSendBodyData bytesSent: Int64,
  102. totalBytesSent: Int64,
  103. totalBytesExpectedToSend: Int64) {
  104. eventMonitor?.urlSession(session,
  105. task: task,
  106. didSendBodyData: bytesSent,
  107. totalBytesSent: totalBytesSent,
  108. totalBytesExpectedToSend: totalBytesExpectedToSend)
  109. stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent,
  110. totalBytesExpectedToSend: totalBytesExpectedToSend)
  111. }
  112. open func urlSession(_ session: URLSession,
  113. task: URLSessionTask,
  114. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  115. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  116. guard let request = stateProvider?.request(for: task) as? UploadRequest else {
  117. fatalError("needNewBodyStream for request that isn't UploadRequest.")
  118. }
  119. completionHandler(request.inputStream())
  120. }
  121. open func urlSession(_ session: URLSession,
  122. task: URLSessionTask,
  123. willPerformHTTPRedirection response: HTTPURLResponse,
  124. newRequest request: URLRequest,
  125. completionHandler: @escaping (URLRequest?) -> Void) {
  126. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  127. if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler {
  128. redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler)
  129. } else {
  130. completionHandler(request)
  131. }
  132. }
  133. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  134. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  135. stateProvider?.request(for: task)?.didGatherMetrics(metrics)
  136. stateProvider?.didGatherMetricsForTask(task)
  137. }
  138. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  139. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  140. stateProvider?.request(for: task)?.didCompleteTask(task, with: error)
  141. stateProvider?.didCompleteTask(task)
  142. }
  143. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  144. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  145. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  146. }
  147. }
  148. extension SessionDelegate: URLSessionDataDelegate {
  149. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  150. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  151. guard let request = stateProvider?.request(for: dataTask) as? DataRequest else {
  152. fatalError("dataTask received data for incorrect Request subclass: \(String(describing: stateProvider?.request(for: dataTask)))")
  153. }
  154. request.didReceive(data: data)
  155. }
  156. open func urlSession(_ session: URLSession,
  157. dataTask: URLSessionDataTask,
  158. willCacheResponse proposedResponse: CachedURLResponse,
  159. completionHandler: @escaping (CachedURLResponse?) -> Void) {
  160. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  161. if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler {
  162. handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler)
  163. } else {
  164. completionHandler(proposedResponse)
  165. }
  166. }
  167. }
  168. extension SessionDelegate: URLSessionDownloadDelegate {
  169. open func urlSession(_ session: URLSession,
  170. downloadTask: URLSessionDownloadTask,
  171. didResumeAtOffset fileOffset: Int64,
  172. expectedTotalBytes: Int64) {
  173. eventMonitor?.urlSession(session,
  174. downloadTask: downloadTask,
  175. didResumeAtOffset: fileOffset,
  176. expectedTotalBytes: expectedTotalBytes)
  177. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  178. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  179. }
  180. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  181. totalBytesExpectedToWrite: expectedTotalBytes)
  182. }
  183. open func urlSession(_ session: URLSession,
  184. downloadTask: URLSessionDownloadTask,
  185. didWriteData bytesWritten: Int64,
  186. totalBytesWritten: Int64,
  187. totalBytesExpectedToWrite: Int64) {
  188. eventMonitor?.urlSession(session,
  189. downloadTask: downloadTask,
  190. didWriteData: bytesWritten,
  191. totalBytesWritten: totalBytesWritten,
  192. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  193. guard let downloadRequest = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  194. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  195. }
  196. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  197. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  198. }
  199. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  200. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  201. guard let request = stateProvider?.request(for: downloadTask) as? DownloadRequest else {
  202. fatalError("Download finished but either no request found or request wasn't DownloadRequest")
  203. }
  204. guard let response = request.response else {
  205. fatalError("URLSessionDownloadTask finished downloading with no response.")
  206. }
  207. let (destination, options) = (request.destination ?? DownloadRequest.defaultDestination)(location, response)
  208. eventMonitor?.request(request, didCreateDestinationURL: destination)
  209. do {
  210. if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) {
  211. try fileManager.removeItem(at: destination)
  212. }
  213. if options.contains(.createIntermediateDirectories) {
  214. let directory = destination.deletingLastPathComponent()
  215. try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
  216. }
  217. try fileManager.moveItem(at: location, to: destination)
  218. request.didFinishDownloading(using: downloadTask, with: .success(destination))
  219. } catch {
  220. request.didFinishDownloading(using: downloadTask, with: .failure(error))
  221. }
  222. }
  223. }