Request.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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
  155. downloadDelegate = delegate as? DownloadTaskDelegate,
  156. downloadTask = downloadDelegate.downloadTask
  157. {
  158. downloadTask.cancel { data in
  159. downloadDelegate.resumeData = data
  160. }
  161. } else {
  162. task.cancel()
  163. }
  164. NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.Task.DidCancel), object: task)
  165. }
  166. // MARK: - TaskDelegate
  167. /**
  168. The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  169. executing all operations attached to the serial operation queue upon task completion.
  170. */
  171. public class TaskDelegate: NSObject {
  172. /// The serial operation queue used to execute all operations after the task completes.
  173. public let queue: OperationQueue
  174. let task: URLSessionTask
  175. let progress: Progress
  176. var data: Data? { return nil }
  177. var error: NSError?
  178. var initialResponseTime: CFAbsoluteTime?
  179. var credential: URLCredential?
  180. init(task: URLSessionTask) {
  181. self.task = task
  182. self.progress = Progress(totalUnitCount: 0)
  183. self.queue = {
  184. let operationQueue = OperationQueue()
  185. operationQueue.maxConcurrentOperationCount = 1
  186. operationQueue.isSuspended = true
  187. if #available(OSX 10.10, *) {
  188. operationQueue.qualityOfService = QualityOfService.utility
  189. }
  190. return operationQueue
  191. }()
  192. }
  193. deinit {
  194. queue.cancelAllOperations()
  195. queue.isSuspended = false
  196. }
  197. // MARK: - NSURLSessionTaskDelegate
  198. // MARK: Override Closures
  199. var taskWillPerformHTTPRedirection: ((Foundation.URLSession, URLSessionTask, HTTPURLResponse, Foundation.URLRequest) -> Foundation.URLRequest?)?
  200. var taskDidReceiveChallenge: ((Foundation.URLSession, URLSessionTask, URLAuthenticationChallenge) -> (Foundation.URLSession.AuthChallengeDisposition, URLCredential?))?
  201. var taskNeedNewBodyStream: ((Foundation.URLSession, URLSessionTask) -> InputStream?)?
  202. var taskDidCompleteWithError: ((Foundation.URLSession, URLSessionTask, NSError?) -> Void)?
  203. // MARK: Delegate Methods
  204. // RDAR
  205. @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
  206. func urlSession(
  207. _ session: Foundation.URLSession,
  208. task: URLSessionTask,
  209. willPerformHTTPRedirection response: HTTPURLResponse,
  210. newRequest request: Foundation.URLRequest,
  211. completionHandler: ((Foundation.URLRequest?) -> Void))
  212. {
  213. var redirectRequest: Foundation.URLRequest? = request
  214. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  215. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  216. }
  217. completionHandler(redirectRequest)
  218. }
  219. @objc(URLSession:task:didReceiveChallenge:completionHandler:)
  220. func urlSession(
  221. _ session: Foundation.URLSession,
  222. task: URLSessionTask,
  223. didReceive challenge: URLAuthenticationChallenge,
  224. completionHandler: ((Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void))
  225. {
  226. var disposition: Foundation.URLSession.AuthChallengeDisposition = .performDefaultHandling
  227. var credential: URLCredential?
  228. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  229. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  230. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  231. let host = challenge.protectionSpace.host
  232. if let
  233. serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
  234. serverTrust = challenge.protectionSpace.serverTrust
  235. {
  236. if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
  237. disposition = .useCredential
  238. credential = URLCredential(trust: serverTrust)
  239. } else {
  240. disposition = .cancelAuthenticationChallenge
  241. }
  242. }
  243. } else {
  244. if challenge.previousFailureCount > 0 {
  245. disposition = .rejectProtectionSpace
  246. } else {
  247. credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
  248. if credential != nil {
  249. disposition = .useCredential
  250. }
  251. }
  252. }
  253. completionHandler(disposition, credential)
  254. }
  255. @objc(URLSession:task:needNewBodyStream:)
  256. func urlSession(
  257. _ session: Foundation.URLSession,
  258. task: URLSessionTask,
  259. needNewBodyStream completionHandler: ((InputStream?) -> Void))
  260. {
  261. var bodyStream: InputStream?
  262. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  263. bodyStream = taskNeedNewBodyStream(session, task)
  264. }
  265. completionHandler(bodyStream)
  266. }
  267. @objc(URLSession:task:didCompleteWithError:)
  268. func urlSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  269. if let taskDidCompleteWithError = taskDidCompleteWithError {
  270. taskDidCompleteWithError(session, task, error)
  271. } else {
  272. if let error = error {
  273. self.error = error
  274. if let
  275. downloadDelegate = self as? DownloadTaskDelegate,
  276. userInfo = error.userInfo as? [String: AnyObject],
  277. resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  278. {
  279. downloadDelegate.resumeData = resumeData
  280. }
  281. }
  282. queue.isSuspended = false
  283. }
  284. }
  285. }
  286. // MARK: - DataTaskDelegate
  287. class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
  288. var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask }
  289. private var totalBytesReceived: Int64 = 0
  290. private var mutableData: NSMutableData
  291. override var data: Data? {
  292. if dataStream != nil {
  293. return nil
  294. } else {
  295. return mutableData as Data
  296. }
  297. }
  298. private var expectedContentLength: Int64?
  299. private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  300. private var dataStream: ((data: Data) -> Void)?
  301. override init(task: URLSessionTask) {
  302. mutableData = NSMutableData()
  303. super.init(task: task)
  304. }
  305. // MARK: - NSURLSessionDataDelegate
  306. // MARK: Override Closures
  307. var dataTaskDidReceiveResponse: ((Foundation.URLSession, URLSessionDataTask, URLResponse) -> Foundation.URLSession.ResponseDisposition)?
  308. var dataTaskDidBecomeDownloadTask: ((Foundation.URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  309. var dataTaskDidReceiveData: ((Foundation.URLSession, URLSessionDataTask, Data) -> Void)?
  310. var dataTaskWillCacheResponse: ((Foundation.URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  311. // MARK: Delegate Methods
  312. func urlSession(
  313. _ session: URLSession,
  314. dataTask: URLSessionDataTask,
  315. didReceive response: URLResponse,
  316. completionHandler: ((Foundation.URLSession.ResponseDisposition) -> Void))
  317. {
  318. var disposition: Foundation.URLSession.ResponseDisposition = .allow
  319. expectedContentLength = response.expectedContentLength
  320. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  321. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  322. }
  323. completionHandler(disposition)
  324. }
  325. func urlSession(
  326. _ session: URLSession,
  327. dataTask: URLSessionDataTask,
  328. didBecome downloadTask: URLSessionDownloadTask)
  329. {
  330. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  331. }
  332. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  333. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  334. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  335. dataTaskDidReceiveData(session, dataTask, data)
  336. } else {
  337. if let dataStream = dataStream {
  338. dataStream(data: data)
  339. } else {
  340. mutableData.append(data)
  341. }
  342. totalBytesReceived += data.count
  343. let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  344. progress.totalUnitCount = totalBytesExpected
  345. progress.completedUnitCount = totalBytesReceived
  346. dataProgress?(
  347. bytesReceived: Int64(data.count),
  348. totalBytesReceived: totalBytesReceived,
  349. totalBytesExpectedToReceive: totalBytesExpected
  350. )
  351. }
  352. }
  353. func urlSession(
  354. _ session: URLSession,
  355. dataTask: URLSessionDataTask,
  356. willCacheResponse proposedResponse: CachedURLResponse,
  357. completionHandler: ((CachedURLResponse?) -> Void))
  358. {
  359. var cachedResponse: CachedURLResponse? = proposedResponse
  360. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  361. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  362. }
  363. completionHandler(cachedResponse)
  364. }
  365. }
  366. }
  367. // MARK: - CustomStringConvertible
  368. extension Request: CustomStringConvertible {
  369. /**
  370. The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  371. well as the response status code if a response has been received.
  372. */
  373. public var description: String {
  374. var components: [String] = []
  375. if let HTTPMethod = request?.httpMethod {
  376. components.append(HTTPMethod)
  377. }
  378. if let URLString = request?.url?.absoluteString {
  379. components.append(URLString)
  380. }
  381. if let response = response {
  382. components.append("(\(response.statusCode))")
  383. }
  384. return components.joined(separator: " ")
  385. }
  386. }
  387. // MARK: - CustomDebugStringConvertible
  388. extension Request: CustomDebugStringConvertible {
  389. func cURLRepresentation() -> String {
  390. var components = ["$ curl -i"]
  391. guard let
  392. request = self.request,
  393. URL = request.url,
  394. host = URL.host
  395. else {
  396. return "$ curl command could not be created"
  397. }
  398. if let HTTPMethod = request.httpMethod where HTTPMethod != "GET" {
  399. components.append("-X \(HTTPMethod)")
  400. }
  401. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  402. let protectionSpace = URLProtectionSpace(
  403. host: host,
  404. port: (URL as NSURL).port?.intValue ?? 0,
  405. protocol: URL.scheme,
  406. realm: host,
  407. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  408. )
  409. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  410. for credential in credentials {
  411. components.append("-u \(credential.user!):\(credential.password!)")
  412. }
  413. } else {
  414. if let credential = delegate.credential {
  415. components.append("-u \(credential.user!):\(credential.password!)")
  416. }
  417. }
  418. }
  419. if session.configuration.httpShouldSetCookies {
  420. if let
  421. cookieStorage = session.configuration.httpCookieStorage,
  422. cookies = cookieStorage.cookies(for: URL) where !cookies.isEmpty
  423. {
  424. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
  425. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  426. }
  427. }
  428. var headers: [NSObject: AnyObject] = [:]
  429. if let additionalHeaders = session.configuration.httpAdditionalHeaders {
  430. for (field, value) in additionalHeaders where field != "Cookie" {
  431. headers[field] = value
  432. }
  433. }
  434. if let headerFields = request.allHTTPHeaderFields {
  435. for (field, value) in headerFields where field != "Cookie" {
  436. headers[field] = value
  437. }
  438. }
  439. for (field, value) in headers {
  440. components.append("-H \"\(field): \(value)\"")
  441. }
  442. if let
  443. HTTPBodyData = request.httpBody,
  444. HTTPBody = String(data: HTTPBodyData, encoding: String.Encoding.utf8)
  445. {
  446. var escapedBody = HTTPBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  447. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  448. components.append("-d \"\(escapedBody)\"")
  449. }
  450. components.append("\"\(URL.absoluteString!)\"")
  451. return components.joined(separator: " \\\n\t")
  452. }
  453. /// The textual representation used when written to an output stream, in the form of a cURL command.
  454. public var debugDescription: String {
  455. return cURLRepresentation()
  456. }
  457. }