Request.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. //
  2. // Request.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. /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
  26. /// handling.
  27. open class Request {
  28. /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
  29. /// `cancel()` on the `Request`.
  30. ///
  31. /// - initialized: Initial state of the `Request`.
  32. /// - resumed: Set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
  33. /// them in this state.
  34. /// - suspended: Set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
  35. /// them in this state.
  36. /// - cancelled: Set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
  37. /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer
  38. /// transition to any other state.
  39. public enum State {
  40. case initialized, resumed, suspended, cancelled
  41. /// Determines whether `self` can be transitioned to `state`.
  42. func canTransitionTo(_ state: State) -> Bool {
  43. switch (self, state) {
  44. case (.initialized, _): return true
  45. case (_, .initialized), (.cancelled, _): return false
  46. case (.resumed, .cancelled), (.suspended, .cancelled),
  47. (.resumed, .suspended), (.suspended, .resumed): return true
  48. case (.suspended, .suspended), (.resumed, .resumed): return false
  49. }
  50. }
  51. }
  52. // MARK: - Initial State
  53. /// `UUID` prividing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
  54. public let id: UUID
  55. /// The serial queue for all internal async actions.
  56. public let underlyingQueue: DispatchQueue
  57. /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
  58. public let serializationQueue: DispatchQueue
  59. /// `EventMonitor` used for event callbacks.
  60. public let eventMonitor: EventMonitor?
  61. /// The `Request`'s delegate.
  62. public weak var delegate: RequestDelegate?
  63. /// `OperationQueue` used internally to enqueue response callbacks. Starts suspended but is activated when the
  64. /// `Request` is finished.
  65. let internalQueue: OperationQueue
  66. // MARK: - Updated State
  67. /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
  68. private struct MutableState {
  69. /// State of the `Request`.
  70. var state: State = .initialized
  71. /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
  72. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  73. /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
  74. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  75. /// `URLCredential` used for authentication challenges.
  76. var credential: URLCredential?
  77. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  78. var requests: [URLRequest] = []
  79. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  80. var tasks: [URLSessionTask] = []
  81. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  82. /// exactly the the `tasks` created.
  83. var metrics: [URLSessionTaskMetrics] = []
  84. /// Number of times any retriers provided retried the `Request`.
  85. var retryCount = 0
  86. /// Final `Error` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  87. var error: Error?
  88. }
  89. /// Protected `MutableState` value that provides threadsafe access to state values.
  90. private let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  91. /// `State` of the `Request`.
  92. public fileprivate(set) var state: State {
  93. get { return protectedMutableState.directValue.state }
  94. set { protectedMutableState.write { $0.state = newValue } }
  95. }
  96. /// Returns whether `state` is `.cancelled`.
  97. public var isCancelled: Bool { return state == .cancelled }
  98. /// Returns whether `state is `.resumed`.
  99. public var isResumed: Bool { return state == .resumed }
  100. /// Returns whether `state` is `.suspended`.
  101. public var isSuspended: Bool { return state == .suspended }
  102. /// Returns whether `state` is `.initialized`.
  103. public var isInitialized: Bool { return state == .initialized }
  104. // Progress
  105. /// Closure type executed when monitoring the upload or download progress of a request.
  106. public typealias ProgressHandler = (Progress) -> Void
  107. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  108. public let uploadProgress = Progress(totalUnitCount: 0)
  109. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  110. public let downloadProgress = Progress(totalUnitCount: 0)
  111. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  112. fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  113. get { return protectedMutableState.directValue.uploadProgressHandler }
  114. set { protectedMutableState.write { $0.uploadProgressHandler = newValue } }
  115. }
  116. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  117. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  118. get { return protectedMutableState.directValue.downloadProgressHandler }
  119. set { protectedMutableState.write { $0.downloadProgressHandler = newValue } }
  120. }
  121. // Credential
  122. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  123. public private(set) var credential: URLCredential? {
  124. get { return protectedMutableState.directValue.credential }
  125. set { protectedMutableState.write { $0.credential = newValue } }
  126. }
  127. // Validators
  128. /// `Validator` callback closures that store the validation calls enqueued.
  129. fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([])
  130. // Requests
  131. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  132. public var requests: [URLRequest] { return protectedMutableState.directValue.requests }
  133. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  134. public var firstRequest: URLRequest? { return requests.first }
  135. /// Last `URLRequest` created on behalf of the `Request`.
  136. public var lastRequest: URLRequest? { return requests.last }
  137. /// Current `URLRequest` created on behalf of the `Request`.
  138. public var request: URLRequest? { return lastRequest }
  139. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`.
  140. public var performedRequests: [URLRequest] {
  141. return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } }
  142. }
  143. // Response
  144. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  145. /// last `URLSessionTask`.
  146. public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse }
  147. // Tasks
  148. /// All `URLSessionTask`s created on behalf of the `Request`.
  149. public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks }
  150. /// First `URLSessionTask` created on behalf of the `Request`.
  151. public var firstTask: URLSessionTask? { return tasks.first }
  152. /// Last `URLSessionTask` crated on behalf of the `Request`.
  153. public var lastTask: URLSessionTask? { return tasks.last }
  154. /// Current `URLSessionTask` created on behalf of the `Request`.
  155. public var task: URLSessionTask? { return lastTask }
  156. // Metrics
  157. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  158. public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics }
  159. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  160. public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first }
  161. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  162. public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last }
  163. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  164. public var metrics: URLSessionTaskMetrics? { return lastMetrics }
  165. /// Number of times the `Request` has been retried.
  166. public var retryCount: Int { return protectedMutableState.directValue.retryCount }
  167. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  168. fileprivate(set) public var error: Error? {
  169. get { return protectedMutableState.directValue.error }
  170. set { protectedMutableState.write { $0.error = newValue } }
  171. }
  172. /// Default initializer for the `Request` superclass.
  173. ///
  174. /// - Parameters:
  175. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. Defaults to a random `UUID`.
  176. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  177. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. Targets the
  178. /// `underlyingQueue` when created by a `SessionManager`.
  179. /// - eventMonitor: `EventMonitor` used for event callbacks from internal `Request` actions.
  180. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  181. public init(id: UUID = UUID(),
  182. underlyingQueue: DispatchQueue,
  183. serializationQueue: DispatchQueue,
  184. eventMonitor: EventMonitor?,
  185. delegate: RequestDelegate) {
  186. self.id = id
  187. self.underlyingQueue = underlyingQueue
  188. self.serializationQueue = serializationQueue
  189. internalQueue = OperationQueue(maxConcurrentOperationCount: 1,
  190. underlyingQueue: underlyingQueue,
  191. name: "org.alamofire.request-\(id)",
  192. startSuspended: true)
  193. self.eventMonitor = eventMonitor
  194. self.delegate = delegate
  195. }
  196. // MARK: - Internal API
  197. // Called from underlyingQueue.
  198. /// Called when a `URLRequest` has been created on behalf of the `Request`.
  199. ///
  200. /// - Parameter request: `URLRequest` created.
  201. func didCreateURLRequest(_ request: URLRequest) {
  202. protectedMutableState.write { $0.requests.append(request) }
  203. eventMonitor?.request(self, didCreateURLRequest: request)
  204. }
  205. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. Triggers retry.
  206. ///
  207. /// - Parameter error: `Error` thrown from the failed creation.
  208. func didFailToCreateURLRequest(with error: Error) {
  209. self.error = error
  210. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  211. retryOrFinish(error: error)
  212. }
  213. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  214. ///
  215. /// - Parameters:
  216. /// - initialRequest: The `URLRequest` that was adapted.
  217. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  218. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  219. protectedMutableState.write { $0.requests.append(adaptedRequest) }
  220. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  221. }
  222. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. Triggers retry.
  223. ///
  224. /// - Parameters:
  225. /// - request: The `URLRequest` the adapter was called with.
  226. /// - error: The `Error` returned by the `RequestAdapter`.
  227. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: Error) {
  228. self.error = error
  229. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  230. retryOrFinish(error: error)
  231. }
  232. /// Called when a `URLSessionTask` is created on behalf of the `Request`. Calls `reset()`.
  233. ///
  234. /// - Parameter task: The `URLSessionTask` created.
  235. func didCreateTask(_ task: URLSessionTask) {
  236. protectedMutableState.write { $0.tasks.append(task) }
  237. reset()
  238. eventMonitor?.request(self, didCreateTask: task)
  239. }
  240. /// Called when resumption is completed.
  241. func didResume() {
  242. eventMonitor?.requestDidResume(self)
  243. }
  244. /// Called when suspension is completed.
  245. func didSuspend() {
  246. eventMonitor?.requestDidSuspend(self)
  247. }
  248. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  249. func didCancel() {
  250. error = AFError.explicitlyCancelled
  251. eventMonitor?.requestDidCancel(self)
  252. }
  253. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the `Request`.
  254. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  255. protectedMutableState.write { $0.metrics.append(metrics) }
  256. eventMonitor?.request(self, didGatherMetrics: metrics)
  257. }
  258. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  259. func didFailTask(_ task: URLSessionTask, earlyWithError error: Error) {
  260. self.error = error
  261. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  262. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  263. }
  264. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  265. func didCompleteTask(_ task: URLSessionTask, with error: Error?) {
  266. self.error = self.error ?? error
  267. protectedValidators.directValue.forEach { $0() }
  268. eventMonitor?.request(self, didCompleteTask: task, with: error)
  269. retryOrFinish(error: self.error)
  270. }
  271. /// Called when the `RequestDelegate` is retrying this `Request`.
  272. func requestIsRetrying() {
  273. protectedMutableState.write { $0.retryCount += 1 }
  274. eventMonitor?.requestIsRetrying(self)
  275. }
  276. /// Called to trigger retry or finish this `Request`.
  277. func retryOrFinish(error: Error?) {
  278. if let error = error, delegate?.willRetryRequest(self) == true {
  279. delegate?.retryRequest(self, ifNecessaryWithError: error)
  280. return
  281. } else {
  282. finish()
  283. }
  284. }
  285. /// Finishes this `Request` and starts the response serializers.
  286. func finish() {
  287. // Start response handlers
  288. internalQueue.isSuspended = false
  289. eventMonitor?.requestDidFinish(self)
  290. }
  291. /// Resets all task related state for retry.
  292. func reset() {
  293. error = nil
  294. uploadProgress.totalUnitCount = 0
  295. uploadProgress.completedUnitCount = 0
  296. downloadProgress.totalUnitCount = 0
  297. downloadProgress.completedUnitCount = 0
  298. }
  299. /// Called when updating the upload progress.
  300. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  301. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  302. uploadProgress.completedUnitCount = totalBytesSent
  303. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  304. }
  305. // MARK: Task Creation
  306. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  307. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  308. fatalError("Subclasses must override.")
  309. }
  310. // MARK: - Public API
  311. // These APIs are callable from any queue.
  312. // MARK: - State
  313. /// Cancels the `Request`. Once cancelled, a `Request` can no longer be resumed or suspended.
  314. ///
  315. /// - Returns: The `Request`.
  316. @discardableResult
  317. open func cancel() -> Self {
  318. guard state.canTransitionTo(.cancelled) else { return self }
  319. state = .cancelled
  320. delegate?.cancelRequest(self)
  321. return self
  322. }
  323. /// Suspends the `Request`.
  324. ///
  325. /// - Returns: The `Request`.
  326. @discardableResult
  327. open func suspend() -> Self {
  328. guard state.canTransitionTo(.suspended) else { return self }
  329. state = .suspended
  330. delegate?.suspendRequest(self)
  331. return self
  332. }
  333. /// Resumes the `Request`.
  334. ///
  335. /// - Returns: The `Request`.
  336. @discardableResult
  337. open func resume() -> Self {
  338. guard state.canTransitionTo(.resumed) else { return self }
  339. state = .resumed
  340. delegate?.resumeRequest(self)
  341. return self
  342. }
  343. // MARK: - Closure API
  344. /// Associates a credential using the provided values with the `Request`.
  345. ///
  346. /// - Parameters:
  347. /// - username: The username.
  348. /// - password: The password.
  349. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`.
  350. /// - Returns: The `Request`.
  351. @discardableResult
  352. open func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  353. let credential = URLCredential(user: username, password: password, persistence: persistence)
  354. return authenticate(with: credential)
  355. }
  356. /// Associates the provided credential with the `Request`.
  357. ///
  358. /// - Parameter credential: The `URLCredential`.
  359. /// - Returns: The `Request`.
  360. @discardableResult
  361. open func authenticate(with credential: URLCredential) -> Self {
  362. protectedMutableState.write { $0.credential = credential }
  363. return self
  364. }
  365. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  366. ///
  367. /// - parameter queue: The dispatch queue to execute the closure on.
  368. /// - parameter closure: The code to be executed periodically as data is read from the server.
  369. ///
  370. /// - returns: The request.
  371. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  372. ///
  373. /// Only the last closure provided is used.
  374. ///
  375. /// - Parameters:
  376. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  377. /// - closure: The code to be executed periodically as data is read from the server.
  378. /// - Returns: The `Request`.
  379. @discardableResult
  380. open func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  381. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  382. return self
  383. }
  384. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is sent to the server.
  385. ///
  386. /// Only the last closure provided is used.
  387. ///
  388. /// - Parameters:
  389. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  390. /// - closure: The closure to be executed periodically as data is sent to the server.
  391. /// - Returns: The `Request`.
  392. @discardableResult
  393. open func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  394. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  395. return self
  396. }
  397. }
  398. // MARK: - Protocol Conformances
  399. extension Request: Equatable {
  400. public static func == (lhs: Request, rhs: Request) -> Bool {
  401. return lhs.id == rhs.id
  402. }
  403. }
  404. extension Request: Hashable {
  405. public var hashValue: Int {
  406. return id.hashValue
  407. }
  408. }
  409. extension Request: CustomStringConvertible {
  410. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  411. /// created, as well as the response status code, if a response has been received.
  412. public var description: String {
  413. guard let request = performedRequests.last ?? lastRequest,
  414. let url = request.url,
  415. let method = request.httpMethod else { return "No request created yet." }
  416. let requestDescription = "\(method) \(url.absoluteString)"
  417. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  418. }
  419. }
  420. extension Request: CustomDebugStringConvertible {
  421. /// A textual representation of this instance in the form of a cURL command.
  422. public var debugDescription: String {
  423. return cURLRepresentation()
  424. }
  425. func cURLRepresentation() -> String {
  426. guard
  427. let request = lastRequest,
  428. let url = request.url,
  429. let host = url.host,
  430. let method = request.httpMethod else { return "$ curl command could not be created" }
  431. var components = ["$ curl -v"]
  432. components.append("-X \(method)")
  433. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  434. let protectionSpace = URLProtectionSpace(
  435. host: host,
  436. port: url.port ?? 0,
  437. protocol: url.scheme,
  438. realm: host,
  439. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  440. )
  441. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  442. for credential in credentials {
  443. guard let user = credential.user, let password = credential.password else { continue }
  444. components.append("-u \(user):\(password)")
  445. }
  446. } else {
  447. if let credential = credential, let user = credential.user, let password = credential.password {
  448. components.append("-u \(user):\(password)")
  449. }
  450. }
  451. }
  452. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  453. if
  454. let cookieStorage = configuration.httpCookieStorage,
  455. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  456. {
  457. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  458. components.append("-b \"\(allCookies)\"")
  459. }
  460. }
  461. var headers: [String: String] = [:]
  462. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  463. for (field, value) in additionalHeaders where field != "Cookie" {
  464. headers[field] = value
  465. }
  466. }
  467. if let headerFields = request.allHTTPHeaderFields {
  468. for (field, value) in headerFields where field != "Cookie" {
  469. headers[field] = value
  470. }
  471. }
  472. for (field, value) in headers {
  473. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  474. components.append("-H \"\(field): \(escapedValue)\"")
  475. }
  476. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  477. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  478. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  479. components.append("-d \"\(escapedBody)\"")
  480. }
  481. components.append("\"\(url.absoluteString)\"")
  482. return components.joined(separator: " \\\n\t")
  483. }
  484. }
  485. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  486. public protocol RequestDelegate: AnyObject {
  487. var sessionConfiguration: URLSessionConfiguration { get }
  488. func willRetryRequest(_ request: Request) -> Bool
  489. func retryRequest(_ request: Request, ifNecessaryWithError error: Error)
  490. func cancelRequest(_ request: Request)
  491. func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void)
  492. func suspendRequest(_ request: Request)
  493. func resumeRequest(_ request: Request)
  494. }
  495. // MARK: - Subclasses
  496. // MARK: DataRequest
  497. open class DataRequest: Request {
  498. public let convertible: URLRequestConvertible
  499. private var protectedData: Protector<Data?> = Protector(nil)
  500. public var data: Data? { return protectedData.directValue }
  501. init(id: UUID = UUID(),
  502. convertible: URLRequestConvertible,
  503. underlyingQueue: DispatchQueue,
  504. serializationQueue: DispatchQueue,
  505. eventMonitor: EventMonitor?,
  506. delegate: RequestDelegate) {
  507. self.convertible = convertible
  508. super.init(id: id,
  509. underlyingQueue: underlyingQueue,
  510. serializationQueue: serializationQueue,
  511. eventMonitor: eventMonitor,
  512. delegate: delegate)
  513. }
  514. override func reset() {
  515. super.reset()
  516. protectedData.directValue = nil
  517. }
  518. func didReceive(data: Data) {
  519. if self.data == nil {
  520. protectedData.directValue = data
  521. } else {
  522. protectedData.append(data)
  523. }
  524. updateDownloadProgress()
  525. }
  526. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  527. let copiedRequest = request
  528. return session.dataTask(with: copiedRequest)
  529. }
  530. func updateDownloadProgress() {
  531. let totalBytesRecieved = Int64(data?.count ?? 0)
  532. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  533. downloadProgress.totalUnitCount = totalBytesExpected
  534. downloadProgress.completedUnitCount = totalBytesRecieved
  535. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  536. }
  537. /// Validates the request, using the specified closure.
  538. ///
  539. /// If validation fails, subsequent calls to response handlers will have an associated error.
  540. ///
  541. /// - parameter validation: A closure to validate the request.
  542. ///
  543. /// - returns: The request.
  544. @discardableResult
  545. public func validate(_ validation: @escaping Validation) -> Self {
  546. let validator: () -> Void = { [unowned self] in
  547. guard self.error == nil, let response = self.response else { return }
  548. let result = validation(self.request, response, self.data)
  549. result.withError { self.error = $0 }
  550. self.eventMonitor?.request(self,
  551. didValidateRequest: self.request,
  552. response: response,
  553. data: self.data,
  554. withResult: result)
  555. }
  556. protectedValidators.append(validator)
  557. return self
  558. }
  559. }
  560. open class DownloadRequest: Request {
  561. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  562. /// destination URL.
  563. public struct Options: OptionSet {
  564. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  565. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  566. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  567. public static let removePreviousFile = Options(rawValue: 1 << 1)
  568. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  569. public let rawValue: Int
  570. /// Creates a `DownloadRequest.Options` instance with the specified raw value.
  571. ///
  572. /// - parameter rawValue: The raw bitmask value for the option.
  573. ///
  574. /// - returns: A new `DownloadRequest.Options` instance.
  575. public init(rawValue: Int) {
  576. self.rawValue = rawValue
  577. }
  578. }
  579. /// A closure executed once a download request has successfully completed in order to determine where to move the
  580. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  581. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  582. /// the options defining how the file should be moved.
  583. public typealias Destination = (_ temporaryURL: URL,
  584. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  585. // MARK: Destination
  586. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  587. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  588. ///
  589. /// - parameter directory: The search path directory. `.documentDirectory` by default.
  590. /// - parameter domain: The search path domain mask. `.userDomainMask` by default.
  591. ///
  592. /// - returns: A download file destination closure.
  593. open class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  594. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  595. options: Options = []) -> Destination {
  596. return { (temporaryURL, response) in
  597. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  598. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  599. return (url, options)
  600. }
  601. }
  602. static let defaultDestination: Destination = { (url, _) in
  603. let filename = "Alamofire_\(url.lastPathComponent)"
  604. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  605. return (destination, [])
  606. }
  607. public enum Downloadable {
  608. case request(URLRequestConvertible)
  609. case resumeData(Data)
  610. }
  611. // MARK: Initial State
  612. public let downloadable: Downloadable
  613. let destination: Destination?
  614. // MARK: Updated State
  615. private struct MutableState {
  616. var resumeData: Data?
  617. var fileURL: URL?
  618. }
  619. private let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  620. public var resumeData: Data? { return protectedMutableState.directValue.resumeData }
  621. public var fileURL: URL? { return protectedMutableState.directValue.fileURL }
  622. // MARK: Init
  623. init(id: UUID = UUID(),
  624. downloadable: Downloadable,
  625. underlyingQueue: DispatchQueue,
  626. serializationQueue: DispatchQueue,
  627. eventMonitor: EventMonitor?,
  628. delegate: RequestDelegate,
  629. destination: Destination? = nil) {
  630. self.downloadable = downloadable
  631. self.destination = destination
  632. super.init(id: id,
  633. underlyingQueue: underlyingQueue,
  634. serializationQueue: serializationQueue,
  635. eventMonitor: eventMonitor,
  636. delegate: delegate)
  637. }
  638. override func reset() {
  639. super.reset()
  640. protectedMutableState.write { $0.resumeData = nil }
  641. protectedMutableState.write { $0.fileURL = nil }
  642. }
  643. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL>) {
  644. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  645. result.withValue { url in protectedMutableState.write { $0.fileURL = url } }
  646. .withError { self.error = $0 }
  647. }
  648. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  649. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  650. downloadProgress.completedUnitCount += bytesWritten
  651. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  652. }
  653. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  654. return session.downloadTask(with: request)
  655. }
  656. open func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  657. return session.downloadTask(withResumeData: data)
  658. }
  659. @discardableResult
  660. open override func cancel() -> Self {
  661. guard state.canTransitionTo(.cancelled) else { return self }
  662. state = .cancelled
  663. delegate?.cancelDownloadRequest(self) { (resumeData) in
  664. self.protectedMutableState.write { $0.resumeData = resumeData }
  665. }
  666. eventMonitor?.requestDidCancel(self)
  667. return self
  668. }
  669. /// Validates the request, using the specified closure.
  670. ///
  671. /// If validation fails, subsequent calls to response handlers will have an associated error.
  672. ///
  673. /// - parameter validation: A closure to validate the request.
  674. ///
  675. /// - returns: The request.
  676. @discardableResult
  677. public func validate(_ validation: @escaping Validation) -> Self {
  678. let validator: () -> Void = { [unowned self] in
  679. guard self.error == nil, let response = self.response else { return }
  680. let result = validation(self.request, response, self.fileURL)
  681. result.withError { self.error = $0 }
  682. self.eventMonitor?.request(self,
  683. didValidateRequest: self.request,
  684. response: response,
  685. fileURL: self.fileURL,
  686. withResult: result)
  687. }
  688. protectedValidators.append(validator)
  689. return self
  690. }
  691. }
  692. open class UploadRequest: DataRequest {
  693. public enum Uploadable {
  694. case data(Data)
  695. case file(URL, shouldRemove: Bool)
  696. case stream(InputStream)
  697. }
  698. // MARK: - Initial State
  699. public let upload: UploadableConvertible
  700. // MARK: - Updated State
  701. public var uploadable: Uploadable?
  702. init(id: UUID = UUID(),
  703. convertible: UploadConvertible,
  704. underlyingQueue: DispatchQueue,
  705. serializationQueue: DispatchQueue,
  706. eventMonitor: EventMonitor?,
  707. delegate: RequestDelegate) {
  708. self.upload = convertible
  709. super.init(id: id,
  710. convertible: convertible,
  711. underlyingQueue: underlyingQueue,
  712. serializationQueue: serializationQueue,
  713. eventMonitor: eventMonitor,
  714. delegate: delegate)
  715. // Automatically remove temporary upload files (e.g. multipart form data)
  716. internalQueue.addOperation {
  717. guard
  718. let uploadable = self.uploadable,
  719. case let .file(url, shouldRemove) = uploadable,
  720. shouldRemove else { return }
  721. // TODO: Abstract file manager
  722. try? FileManager.default.removeItem(at: url)
  723. }
  724. }
  725. func didCreateUploadable(_ uploadable: Uploadable) {
  726. self.uploadable = uploadable
  727. eventMonitor?.request(self, didCreateUploadable: uploadable)
  728. }
  729. func didFailToCreateUploadable(with error: Error) {
  730. self.error = error
  731. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  732. retryOrFinish(error: error)
  733. }
  734. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  735. guard let uploadable = uploadable else {
  736. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  737. }
  738. switch uploadable {
  739. case let .data(data): return session.uploadTask(with: request, from: data)
  740. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  741. case .stream: return session.uploadTask(withStreamedRequest: request)
  742. }
  743. }
  744. func inputStream() -> InputStream {
  745. guard let uploadable = uploadable else {
  746. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  747. }
  748. guard case let .stream(stream) = uploadable else {
  749. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  750. }
  751. eventMonitor?.request(self, didProvideInputStream: stream)
  752. return stream
  753. }
  754. }
  755. public protocol UploadableConvertible {
  756. func createUploadable() throws -> UploadRequest.Uploadable
  757. }
  758. extension UploadRequest.Uploadable: UploadableConvertible {
  759. public func createUploadable() throws -> UploadRequest.Uploadable {
  760. return self
  761. }
  762. }
  763. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }