SessionDelegate.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. open class SessionDelegate: NSObject {
  26. private(set) var requestTaskMap = RequestTaskMap()
  27. // TODO: Better way to connect delegate to manager, including queue?
  28. private weak var manager: SessionManager?
  29. private var eventMonitor: EventMonitor?
  30. private var queue: DispatchQueue? { return manager?.rootQueue }
  31. let startRequestsImmediately: Bool
  32. public init(startRequestsImmediately: Bool = true) {
  33. self.startRequestsImmediately = startRequestsImmediately
  34. }
  35. func didCreateSessionManager(_ manager: SessionManager, withEventMonitor eventMonitor: EventMonitor) {
  36. self.manager = manager
  37. self.eventMonitor = eventMonitor
  38. }
  39. func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
  40. guard let manager = manager else { fatalError("Received didCreateURLRequest but there is no manager.") }
  41. guard !request.isCancelled else { return }
  42. let task = request.task(for: urlRequest, using: manager.session)
  43. requestTaskMap[request] = task
  44. request.didCreateTask(task)
  45. resumeOrSuspendTask(task, ifNecessaryForRequest: request)
  46. }
  47. func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
  48. guard let manager = manager else { fatalError("Received didReceiveResumeData but there is no manager.") }
  49. guard !request.isCancelled else { return }
  50. let task = request.task(forResumeData: data, using: manager.session)
  51. requestTaskMap[request] = task
  52. request.didCreateTask(task)
  53. resumeOrSuspendTask(task, ifNecessaryForRequest: request)
  54. }
  55. func resumeOrSuspendTask(_ task: URLSessionTask, ifNecessaryForRequest request: Request) {
  56. if startRequestsImmediately || request.isResumed {
  57. task.resume()
  58. request.didResume()
  59. }
  60. if request.isSuspended {
  61. task.suspend()
  62. request.didSuspend()
  63. }
  64. }
  65. }
  66. extension SessionDelegate: RequestDelegate {
  67. func isRetryingRequest(_ request: Request, ifNecessaryWithError error: Error) -> Bool {
  68. guard let manager = manager, let retrier = manager.retrier else { return false }
  69. retrier.should(manager, retry: request, with: error) { (shouldRetry, retryInterval) in
  70. guard !request.isCancelled else { return }
  71. self.queue?.async {
  72. guard shouldRetry else {
  73. request.finish()
  74. return
  75. }
  76. self.queue?.after(retryInterval) {
  77. guard !request.isCancelled else { return }
  78. self.eventMonitor?.requestIsRetrying(request)
  79. self.manager?.perform(request)
  80. }
  81. }
  82. }
  83. return true
  84. }
  85. func cancelRequest(_ request: Request) {
  86. queue?.async {
  87. guard let task = self.requestTaskMap[request] else {
  88. request.didCancel()
  89. request.finish()
  90. return
  91. }
  92. request.didCancel()
  93. task.cancel()
  94. }
  95. }
  96. func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void) {
  97. queue?.async {
  98. guard let downloadTask = self.requestTaskMap[request] as? URLSessionDownloadTask else {
  99. request.didCancel()
  100. request.finish()
  101. return
  102. }
  103. downloadTask.cancel { (data) in
  104. self.queue?.async {
  105. byProducingResumeData(data)
  106. request.didCancel()
  107. }
  108. }
  109. }
  110. }
  111. func suspendRequest(_ request: Request) {
  112. queue?.async {
  113. defer { request.didSuspend() }
  114. guard !request.isCancelled, let task = self.requestTaskMap[request] else { return }
  115. task.suspend()
  116. }
  117. }
  118. func resumeRequest(_ request: Request) {
  119. queue?.async {
  120. defer { request.didResume() }
  121. guard !request.isCancelled, let task = self.requestTaskMap[request] else { return }
  122. task.resume()
  123. }
  124. }
  125. }
  126. extension SessionDelegate: URLSessionDelegate {
  127. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  128. eventMonitor?.urlSession(session, didBecomeInvalidWithError: error)
  129. }
  130. }
  131. extension SessionDelegate: URLSessionTaskDelegate {
  132. // Auth challenge, will be received always since the URLSessionDelegate method isn't implemented.
  133. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: Error?)
  134. open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  135. eventMonitor?.urlSession(session, task: task, didReceive: challenge)
  136. let evaluation: ChallengeEvaluation
  137. switch challenge.protectionSpace.authenticationMethod {
  138. case NSURLAuthenticationMethodServerTrust:
  139. evaluation = attemptServerTrustAuthentication(with: challenge)
  140. case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest:
  141. evaluation = attemptHTTPAuthentication(for: challenge, belongingTo: task)
  142. // TODO: Error explaining AF doesn't support client certificates?
  143. // case NSURLAuthenticationMethodClientCertificate:
  144. default:
  145. evaluation = (.performDefaultHandling, nil, nil)
  146. }
  147. if let error = evaluation.error {
  148. requestTaskMap[task]?.didFailTask(task, earlyWithError: error)
  149. }
  150. completionHandler(evaluation.disposition, evaluation.credential)
  151. }
  152. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation {
  153. let host = challenge.protectionSpace.host
  154. guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
  155. let evaluator = manager?.serverTrustManager?.serverTrustEvaluators(forHost: host),
  156. let serverTrust = challenge.protectionSpace.serverTrust
  157. else {
  158. return (.performDefaultHandling, nil, nil)
  159. }
  160. guard evaluator.evaluate(serverTrust, forHost: host) else {
  161. let error = AFError.certificatePinningFailed
  162. return (.cancelAuthenticationChallenge, nil, error)
  163. }
  164. return (.useCredential, URLCredential(trust: serverTrust), nil)
  165. }
  166. func attemptHTTPAuthentication(for challenge: URLAuthenticationChallenge, belongingTo task: URLSessionTask) -> ChallengeEvaluation {
  167. guard challenge.previousFailureCount == 0 else {
  168. return (.rejectProtectionSpace, nil, nil)
  169. }
  170. guard let credential = requestTaskMap[task]?.credential ??
  171. manager?.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) else {
  172. return (.performDefaultHandling, nil, nil)
  173. }
  174. return (.useCredential, credential, nil)
  175. }
  176. open func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  177. eventMonitor?.urlSession(session,
  178. task: task,
  179. didSendBodyData: bytesSent,
  180. totalBytesSent: totalBytesSent,
  181. totalBytesExpectedToSend: totalBytesExpectedToSend)
  182. requestTaskMap[task]?.updateUploadProgress(totalBytesSent: totalBytesSent,
  183. totalBytesExpectedToSend: totalBytesExpectedToSend)
  184. }
  185. open func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  186. eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task)
  187. guard let request = requestTaskMap[task] as? UploadRequest else {
  188. fatalError("needNewBodyStream for request that isn't UploadRequest.")
  189. }
  190. completionHandler(request.inputStream())
  191. }
  192. open func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
  193. eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request)
  194. completionHandler(request)
  195. }
  196. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  197. eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics)
  198. requestTaskMap[task]?.didGatherMetrics(metrics)
  199. }
  200. // Task finished transferring data or had a client error.
  201. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  202. eventMonitor?.urlSession(session, task: task, didCompleteWithError: error)
  203. requestTaskMap[task]?.didCompleteTask(task, with: error)
  204. requestTaskMap[task] = nil
  205. }
  206. // Only used when background sessions are resuming a delayed task.
  207. // func urlSession(_ session: URLSession, task: URLSessionTask, willBeginDelayedRequest request: URLRequest, completionHandler: @escaping (URLSession.DelayedRequestDisposition, URLRequest?) -> Void) {
  208. //
  209. // }
  210. // This method is called if the waitsForConnectivity property of URLSessionConfiguration is true, and sufficient
  211. // connectivity is unavailable. The delegate can use this opportunity to update the user interface; for example, by
  212. // presenting an offline mode or a cellular-only mode.
  213. //
  214. // This method is called, at most, once per task, and only if connectivity is initially unavailable. It is never
  215. // called for background sessions because waitsForConnectivity is ignored for those sessions.
  216. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  217. open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  218. eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task)
  219. // Post Notification?
  220. // Update Request state?
  221. // Only once? How to know when it's done waiting and resumes the task?
  222. }
  223. }
  224. extension SessionDelegate: URLSessionDataDelegate {
  225. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  226. eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data)
  227. // TODO: UploadRequest will need this too, only works now because it's a subclass.
  228. guard let request = requestTaskMap[dataTask] as? DataRequest else {
  229. fatalError("dataTask received data for incorrect Request subclass: \(String(describing: requestTaskMap[dataTask]))")
  230. }
  231. request.didRecieve(data: data)
  232. }
  233. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
  234. eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse)
  235. completionHandler(proposedResponse)
  236. }
  237. }
  238. extension SessionDelegate: URLSessionDownloadDelegate {
  239. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  240. eventMonitor?.urlSession(session,
  241. downloadTask: downloadTask,
  242. didResumeAtOffset: fileOffset,
  243. expectedTotalBytes: expectedTotalBytes)
  244. guard let downloadRequest = requestTaskMap[downloadTask] as? DownloadRequest else {
  245. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  246. }
  247. downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
  248. totalBytesExpectedToWrite: expectedTotalBytes)
  249. }
  250. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  251. eventMonitor?.urlSession(session,
  252. downloadTask: downloadTask,
  253. didWriteData: bytesWritten,
  254. totalBytesWritten: totalBytesWritten,
  255. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  256. guard let downloadRequest = requestTaskMap[downloadTask] as? DownloadRequest else {
  257. fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
  258. }
  259. downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
  260. totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  261. }
  262. open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
  263. eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  264. guard let request = requestTaskMap[downloadTask] as? DownloadRequest else {
  265. fatalError("download finished but either no request found or request wasn't DownloadRequest")
  266. }
  267. request.didComplete(task: downloadTask, with: location)
  268. }
  269. }