Request.swift 21 KB

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