2
0

SessionStateProvider.swift 12 KB

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