SessionStateProvider.swift 11 KB

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