Request.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2016 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. /**
  26. Responsible for sending a request and receiving the response and associated data from the server, as well as
  27. managing its underlying `NSURLSessionTask`.
  28. */
  29. public class Request {
  30. // MARK: - Properties
  31. /// The delegate for the underlying task.
  32. public let delegate: TaskDelegate
  33. /// The underlying task.
  34. public var task: URLSessionTask { return delegate.task }
  35. /// The session belonging to the underlying task.
  36. public let session: URLSession
  37. /// The request sent or to be sent to the server.
  38. public var request: Foundation.URLRequest? { return task.originalRequest }
  39. /// The response received from the server, if any.
  40. public var response: HTTPURLResponse? { return task.response as? HTTPURLResponse }
  41. /// The progress of the request lifecycle.
  42. public var progress: Progress { return delegate.progress }
  43. var startTime: CFAbsoluteTime?
  44. var endTime: CFAbsoluteTime?
  45. // MARK: - Lifecycle
  46. init(session: URLSession, task: URLSessionTask) {
  47. self.session = session
  48. switch task {
  49. case is URLSessionUploadTask:
  50. delegate = UploadTaskDelegate(task: task)
  51. case is URLSessionDataTask:
  52. delegate = DataTaskDelegate(task: task)
  53. case is URLSessionDownloadTask:
  54. delegate = DownloadTaskDelegate(task: task)
  55. default:
  56. delegate = TaskDelegate(task: task)
  57. }
  58. delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
  59. }
  60. // MARK: - Authentication
  61. /**
  62. Associates an HTTP Basic credential with the request.
  63. - parameter user: The user.
  64. - parameter password: The password.
  65. - parameter persistence: The URL credential persistence. `.ForSession` by default.
  66. - returns: The request.
  67. */
  68. public func authenticate(
  69. user: String,
  70. password: String,
  71. persistence: URLCredential.Persistence = .forSession)
  72. -> Self
  73. {
  74. let credential = URLCredential(user: user, password: password, persistence: persistence)
  75. return authenticate(usingCredential: credential)
  76. }
  77. /**
  78. Associates a specified credential with the request.
  79. - parameter credential: The credential.
  80. - returns: The request.
  81. */
  82. public func authenticate(usingCredential credential: URLCredential) -> Self {
  83. delegate.credential = credential
  84. return self
  85. }
  86. /**
  87. Returns a base64 encoded basic authentication credential as an authorization header dictionary.
  88. - parameter user: The user.
  89. - parameter password: The password.
  90. - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
  91. */
  92. public static func authorizationHeader(user: String, password: String) -> [String: String] {
  93. guard let data = "\(user):\(password)".data(using: String.Encoding.utf8) else { return [:] }
  94. let credential = data.base64EncodedString(options: [])
  95. return ["Authorization": "Basic \(credential)"]
  96. }
  97. // MARK: - Progress
  98. /**
  99. Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
  100. from the server.
  101. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
  102. to write.
  103. - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
  104. expected to read.
  105. - parameter closure: The code to be executed periodically during the lifecycle of the request.
  106. - returns: The request.
  107. */
  108. @discardableResult
  109. public func progress(_ closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  110. if let uploadDelegate = delegate as? UploadTaskDelegate {
  111. uploadDelegate.uploadProgress = closure
  112. } else if let dataDelegate = delegate as? DataTaskDelegate {
  113. dataDelegate.dataProgress = closure
  114. } else if let downloadDelegate = delegate as? DownloadTaskDelegate {
  115. downloadDelegate.downloadProgress = closure
  116. }
  117. return self
  118. }
  119. /**
  120. Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  121. This closure returns the bytes most recently received from the server, not including data from previous calls.
  122. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  123. also important to note that the `response` closure will be called with nil `responseData`.
  124. - parameter closure: The code to be executed periodically during the lifecycle of the request.
  125. - returns: The request.
  126. */
  127. @discardableResult
  128. public func stream(_ closure: ((Data) -> Void)? = nil) -> Self {
  129. if let dataDelegate = delegate as? DataTaskDelegate {
  130. dataDelegate.dataStream = closure
  131. }
  132. return self
  133. }
  134. // MARK: - State
  135. /**
  136. Resumes the request.
  137. */
  138. public func resume() {
  139. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
  140. task.resume()
  141. NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.Task.DidResume), object: task)
  142. }
  143. /**
  144. Suspends the request.
  145. */
  146. public func suspend() {
  147. task.suspend()
  148. NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.Task.DidSuspend), object: task)
  149. }
  150. /**
  151. Cancels the request.
  152. */
  153. public func cancel() {
  154. if let downloadDelegate = delegate as? DownloadTaskDelegate,
  155. let downloadTask = downloadDelegate.downloadTask
  156. {
  157. downloadTask.cancel { data in
  158. downloadDelegate.resumeData = data
  159. }
  160. } else {
  161. task.cancel()
  162. }
  163. NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.Task.DidCancel), object: task)
  164. }
  165. // MARK: - TaskDelegate
  166. /**
  167. The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  168. executing all operations attached to the serial operation queue upon task completion.
  169. */
  170. public class TaskDelegate: NSObject {
  171. /// The serial operation queue used to execute all operations after the task completes.
  172. public let queue: OperationQueue
  173. let task: URLSessionTask
  174. let progress: Progress
  175. var data: Data? { return nil }
  176. var error: NSError?
  177. var initialResponseTime: CFAbsoluteTime?
  178. var credential: URLCredential?
  179. init(task: URLSessionTask) {
  180. self.task = task
  181. self.progress = Progress(totalUnitCount: 0)
  182. self.queue = {
  183. let operationQueue = OperationQueue()
  184. operationQueue.maxConcurrentOperationCount = 1
  185. operationQueue.isSuspended = true
  186. operationQueue.qualityOfService = .utility
  187. return operationQueue
  188. }()
  189. }
  190. deinit {
  191. queue.cancelAllOperations()
  192. queue.isSuspended = false
  193. }
  194. // MARK: - NSURLSessionTaskDelegate
  195. // MARK: Override Closures
  196. var taskWillPerformHTTPRedirection: ((Foundation.URLSession, URLSessionTask, HTTPURLResponse, Foundation.URLRequest) -> Foundation.URLRequest?)?
  197. var taskDidReceiveChallenge: ((Foundation.URLSession, URLSessionTask, URLAuthenticationChallenge) -> (Foundation.URLSession.AuthChallengeDisposition, URLCredential?))?
  198. var taskNeedNewBodyStream: ((Foundation.URLSession, URLSessionTask) -> InputStream?)?
  199. var taskDidCompleteWithError: ((Foundation.URLSession, URLSessionTask, NSError?) -> Void)?
  200. // MARK: Delegate Methods
  201. // RDAR
  202. @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
  203. func urlSession(
  204. _ session: Foundation.URLSession,
  205. task: URLSessionTask,
  206. willPerformHTTPRedirection response: HTTPURLResponse,
  207. newRequest request: Foundation.URLRequest,
  208. completionHandler: ((Foundation.URLRequest?) -> Void))
  209. {
  210. var redirectRequest: Foundation.URLRequest? = request
  211. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  212. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  213. }
  214. completionHandler(redirectRequest)
  215. }
  216. @objc(URLSession:task:didReceiveChallenge:completionHandler:)
  217. func urlSession(
  218. _ session: Foundation.URLSession,
  219. task: URLSessionTask,
  220. didReceive challenge: URLAuthenticationChallenge,
  221. completionHandler: ((Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void))
  222. {
  223. var disposition: Foundation.URLSession.AuthChallengeDisposition = .performDefaultHandling
  224. var credential: URLCredential?
  225. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  226. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  227. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  228. let host = challenge.protectionSpace.host
  229. if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
  230. let serverTrust = challenge.protectionSpace.serverTrust
  231. {
  232. if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
  233. disposition = .useCredential
  234. credential = URLCredential(trust: serverTrust)
  235. } else {
  236. disposition = .cancelAuthenticationChallenge
  237. }
  238. }
  239. } else {
  240. if challenge.previousFailureCount > 0 {
  241. disposition = .rejectProtectionSpace
  242. } else {
  243. credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
  244. if credential != nil {
  245. disposition = .useCredential
  246. }
  247. }
  248. }
  249. completionHandler(disposition, credential)
  250. }
  251. @objc(URLSession:task:needNewBodyStream:)
  252. func urlSession(
  253. _ session: Foundation.URLSession,
  254. task: URLSessionTask,
  255. needNewBodyStream completionHandler: ((InputStream?) -> Void))
  256. {
  257. var bodyStream: InputStream?
  258. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  259. bodyStream = taskNeedNewBodyStream(session, task)
  260. }
  261. completionHandler(bodyStream)
  262. }
  263. @objc(URLSession:task:didCompleteWithError:)
  264. func urlSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  265. if let taskDidCompleteWithError = taskDidCompleteWithError {
  266. taskDidCompleteWithError(session, task, error)
  267. } else {
  268. if let error = error {
  269. self.error = error
  270. if let downloadDelegate = self as? DownloadTaskDelegate,
  271. let userInfo = error.userInfo as? [String: AnyObject],
  272. let resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  273. {
  274. downloadDelegate.resumeData = resumeData
  275. }
  276. }
  277. queue.isSuspended = false
  278. }
  279. }
  280. }
  281. // MARK: - DataTaskDelegate
  282. class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
  283. var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask }
  284. private var totalBytesReceived: Int64 = 0
  285. private var mutableData: NSMutableData
  286. override var data: Data? {
  287. if dataStream != nil {
  288. return nil
  289. } else {
  290. return mutableData as Data
  291. }
  292. }
  293. private var expectedContentLength: Int64?
  294. private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  295. private var dataStream: ((data: Data) -> Void)?
  296. override init(task: URLSessionTask) {
  297. mutableData = NSMutableData()
  298. super.init(task: task)
  299. }
  300. // MARK: - NSURLSessionDataDelegate
  301. // MARK: Override Closures
  302. var dataTaskDidReceiveResponse: ((Foundation.URLSession, URLSessionDataTask, URLResponse) -> Foundation.URLSession.ResponseDisposition)?
  303. var dataTaskDidBecomeDownloadTask: ((Foundation.URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  304. var dataTaskDidReceiveData: ((Foundation.URLSession, URLSessionDataTask, Data) -> Void)?
  305. var dataTaskWillCacheResponse: ((Foundation.URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  306. // MARK: Delegate Methods
  307. func urlSession(
  308. _ session: URLSession,
  309. dataTask: URLSessionDataTask,
  310. didReceive response: URLResponse,
  311. completionHandler: ((Foundation.URLSession.ResponseDisposition) -> Void))
  312. {
  313. var disposition: Foundation.URLSession.ResponseDisposition = .allow
  314. expectedContentLength = response.expectedContentLength
  315. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  316. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  317. }
  318. completionHandler(disposition)
  319. }
  320. func urlSession(
  321. _ session: URLSession,
  322. dataTask: URLSessionDataTask,
  323. didBecome downloadTask: URLSessionDownloadTask)
  324. {
  325. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  326. }
  327. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  328. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  329. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  330. dataTaskDidReceiveData(session, dataTask, data)
  331. } else {
  332. if let dataStream = dataStream {
  333. dataStream(data: data)
  334. } else {
  335. mutableData.append(data)
  336. }
  337. totalBytesReceived += data.count
  338. let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  339. progress.totalUnitCount = totalBytesExpected
  340. progress.completedUnitCount = totalBytesReceived
  341. dataProgress?(
  342. bytesReceived: Int64(data.count),
  343. totalBytesReceived: totalBytesReceived,
  344. totalBytesExpectedToReceive: totalBytesExpected
  345. )
  346. }
  347. }
  348. func urlSession(
  349. _ session: URLSession,
  350. dataTask: URLSessionDataTask,
  351. willCacheResponse proposedResponse: CachedURLResponse,
  352. completionHandler: ((CachedURLResponse?) -> Void))
  353. {
  354. var cachedResponse: CachedURLResponse? = proposedResponse
  355. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  356. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  357. }
  358. completionHandler(cachedResponse)
  359. }
  360. }
  361. }
  362. // MARK: - CustomStringConvertible
  363. extension Request: CustomStringConvertible {
  364. /**
  365. The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  366. well as the response status code if a response has been received.
  367. */
  368. public var description: String {
  369. var components: [String] = []
  370. if let HTTPMethod = request?.httpMethod {
  371. components.append(HTTPMethod)
  372. }
  373. if let URLString = request?.url?.absoluteString {
  374. components.append(URLString)
  375. }
  376. if let response = response {
  377. components.append("(\(response.statusCode))")
  378. }
  379. return components.joined(separator: " ")
  380. }
  381. }
  382. // MARK: - CustomDebugStringConvertible
  383. extension Request: CustomDebugStringConvertible {
  384. func cURLRepresentation() -> String {
  385. var components = ["$ curl -i"]
  386. guard let request = self.request,
  387. let URL = request.url,
  388. let host = URL.host
  389. else {
  390. return "$ curl command could not be created"
  391. }
  392. if let httpMethod = request.httpMethod, httpMethod != "GET" {
  393. components.append("-X \(httpMethod)")
  394. }
  395. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  396. let protectionSpace = URLProtectionSpace(
  397. host: host,
  398. port: (URL as NSURL).port?.intValue ?? 0,
  399. protocol: URL.scheme,
  400. realm: host,
  401. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  402. )
  403. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  404. for credential in credentials {
  405. components.append("-u \(credential.user!):\(credential.password!)")
  406. }
  407. } else {
  408. if let credential = delegate.credential {
  409. components.append("-u \(credential.user!):\(credential.password!)")
  410. }
  411. }
  412. }
  413. if session.configuration.httpShouldSetCookies {
  414. if let cookieStorage = session.configuration.httpCookieStorage,
  415. let cookies = cookieStorage.cookies(for: URL), !cookies.isEmpty
  416. {
  417. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
  418. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  419. }
  420. }
  421. var headers: [NSObject: AnyObject] = [:]
  422. if let additionalHeaders = session.configuration.httpAdditionalHeaders {
  423. for (field, value) in additionalHeaders where field != "Cookie" {
  424. headers[field] = value
  425. }
  426. }
  427. if let headerFields = request.allHTTPHeaderFields {
  428. for (field, value) in headerFields where field != "Cookie" {
  429. headers[field] = value
  430. }
  431. }
  432. for (field, value) in headers {
  433. components.append("-H \"\(field): \(value)\"")
  434. }
  435. if let httpBodyData = request.httpBody,
  436. let httpBody = String(data: httpBodyData, encoding: String.Encoding.utf8)
  437. {
  438. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  439. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  440. components.append("-d \"\(escapedBody)\"")
  441. }
  442. components.append("\"\(URL.absoluteString!)\"")
  443. return components.joined(separator: " \\\n\t")
  444. }
  445. /// The textual representation used when written to an output stream, in the form of a cURL command.
  446. public var debugDescription: String {
  447. return cURLRepresentation()
  448. }
  449. }