HTTPHeaders.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. //
  2. // HTTPHeaders.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. /// An order-preserving and case-insensitive representation of HTTP headers.
  26. public struct HTTPHeaders {
  27. private var headers: [HTTPHeader] = []
  28. /// Creates an empty instance.
  29. public init() {}
  30. /// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last
  31. /// name and value encountered.
  32. public init(_ headers: [HTTPHeader]) {
  33. headers.forEach { update($0) }
  34. }
  35. /// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name
  36. /// and value encountered.
  37. public init(_ dictionary: [String: String]) {
  38. dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) }
  39. }
  40. /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
  41. ///
  42. /// - Parameters:
  43. /// - name: The `HTTPHeader` name.
  44. /// - value: The `HTTPHeader value.
  45. public mutating func add(name: String, value: String) {
  46. update(HTTPHeader(name: name, value: value))
  47. }
  48. /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
  49. ///
  50. /// - Parameter header: The `HTTPHeader` to update or append.
  51. public mutating func add(_ header: HTTPHeader) {
  52. update(header)
  53. }
  54. /// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
  55. ///
  56. /// - Parameters:
  57. /// - name: The `HTTPHeader` name.
  58. /// - value: The `HTTPHeader value.
  59. public mutating func update(name: String, value: String) {
  60. update(HTTPHeader(name: name, value: value))
  61. }
  62. /// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
  63. ///
  64. /// - Parameter header: The `HTTPHeader` to update or append.
  65. public mutating func update(_ header: HTTPHeader) {
  66. guard let index = headers.index(of: header.name) else {
  67. headers.append(header)
  68. return
  69. }
  70. headers.replaceSubrange(index...index, with: [header])
  71. }
  72. /// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance.
  73. ///
  74. /// - Parameter name: The name of the `HTTPHeader` to remove.
  75. public mutating func remove(name: String) {
  76. guard let index = headers.index(of: name) else { return }
  77. headers.remove(at: index)
  78. }
  79. /// Sort the current instance by header name, case insensitively.
  80. public mutating func sort() {
  81. headers.sort { $0.name.lowercased() < $1.name.lowercased() }
  82. }
  83. /// Returns an instance sorted by header name.
  84. ///
  85. /// - Returns: A copy of the current instance sorted by name.
  86. public func sorted() -> HTTPHeaders {
  87. var headers = self
  88. headers.sort()
  89. return headers
  90. }
  91. /// Case-insensitively find a header's value by name.
  92. ///
  93. /// - Parameter name: The name of the header to search for, case-insensitively.
  94. ///
  95. /// - Returns: The value of header, if it exists.
  96. public func value(for name: String) -> String? {
  97. guard let index = headers.index(of: name) else { return nil }
  98. return headers[index].value
  99. }
  100. /// Case-insensitively access the header with the given name.
  101. ///
  102. /// - Parameter name: The name of the header.
  103. public subscript(_ name: String) -> String? {
  104. get { value(for: name) }
  105. set {
  106. if let value = newValue {
  107. update(name: name, value: value)
  108. } else {
  109. remove(name: name)
  110. }
  111. }
  112. }
  113. /// The dictionary representation of all headers.
  114. ///
  115. /// This representation does not preserve the current order of the instance.
  116. public var dictionary: [String: String] {
  117. let namesAndValues = headers.map { ($0.name, $0.value) }
  118. return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last })
  119. }
  120. }
  121. extension HTTPHeaders: ExpressibleByDictionaryLiteral {
  122. public init(dictionaryLiteral elements: (String, String)...) {
  123. elements.forEach { update(name: $0.0, value: $0.1) }
  124. }
  125. }
  126. extension HTTPHeaders: ExpressibleByArrayLiteral {
  127. public init(arrayLiteral elements: HTTPHeader...) {
  128. self.init(elements)
  129. }
  130. }
  131. extension HTTPHeaders: Sequence {
  132. public func makeIterator() -> IndexingIterator<[HTTPHeader]> {
  133. headers.makeIterator()
  134. }
  135. }
  136. extension HTTPHeaders: Collection {
  137. public var startIndex: Int {
  138. headers.startIndex
  139. }
  140. public var endIndex: Int {
  141. headers.endIndex
  142. }
  143. public subscript(position: Int) -> HTTPHeader {
  144. headers[position]
  145. }
  146. public func index(after i: Int) -> Int {
  147. headers.index(after: i)
  148. }
  149. }
  150. extension HTTPHeaders: CustomStringConvertible {
  151. public var description: String {
  152. headers.map(\.description)
  153. .joined(separator: "\n")
  154. }
  155. }
  156. // MARK: - HTTPHeader
  157. /// A representation of a single HTTP header's name / value pair.
  158. public struct HTTPHeader: Hashable {
  159. /// Name of the header.
  160. public let name: String
  161. /// Value of the header.
  162. public let value: String
  163. /// Creates an instance from the given `name` and `value`.
  164. ///
  165. /// - Parameters:
  166. /// - name: The name of the header.
  167. /// - value: The value of the header.
  168. public init(name: String, value: String) {
  169. self.name = name
  170. self.value = value
  171. }
  172. }
  173. extension HTTPHeader: CustomStringConvertible {
  174. public var description: String {
  175. "\(name): \(value)"
  176. }
  177. }
  178. extension HTTPHeader {
  179. /// Returns an `Accept` header.
  180. ///
  181. /// - Parameter value: The `Accept` value.
  182. /// - Returns: The header.
  183. public static func accept(_ value: String) -> HTTPHeader {
  184. HTTPHeader(name: "Accept", value: value)
  185. }
  186. /// Returns an `Accept-Charset` header.
  187. ///
  188. /// - Parameter value: The `Accept-Charset` value.
  189. /// - Returns: The header.
  190. public static func acceptCharset(_ value: String) -> HTTPHeader {
  191. HTTPHeader(name: "Accept-Charset", value: value)
  192. }
  193. /// Returns an `Accept-Language` header.
  194. ///
  195. /// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages.
  196. /// Use `HTTPHeader.defaultAcceptLanguage`.
  197. ///
  198. /// - Parameter value: The `Accept-Language` value.
  199. ///
  200. /// - Returns: The header.
  201. public static func acceptLanguage(_ value: String) -> HTTPHeader {
  202. HTTPHeader(name: "Accept-Language", value: value)
  203. }
  204. /// Returns an `Accept-Encoding` header.
  205. ///
  206. /// Alamofire offers a default accept encoding value that provides the most common values. Use
  207. /// `HTTPHeader.defaultAcceptEncoding`.
  208. ///
  209. /// - Parameter value: The `Accept-Encoding` value.
  210. ///
  211. /// - Returns: The header
  212. public static func acceptEncoding(_ value: String) -> HTTPHeader {
  213. HTTPHeader(name: "Accept-Encoding", value: value)
  214. }
  215. /// Returns a `Basic` `Authorization` header using the `username` and `password` provided.
  216. ///
  217. /// - Parameters:
  218. /// - username: The username of the header.
  219. /// - password: The password of the header.
  220. ///
  221. /// - Returns: The header.
  222. public static func authorization(username: String, password: String) -> HTTPHeader {
  223. let credential = Data("\(username):\(password)".utf8).base64EncodedString()
  224. return authorization("Basic \(credential)")
  225. }
  226. /// Returns a `Bearer` `Authorization` header using the `bearerToken` provided
  227. ///
  228. /// - Parameter bearerToken: The bearer token.
  229. ///
  230. /// - Returns: The header.
  231. public static func authorization(bearerToken: String) -> HTTPHeader {
  232. authorization("Bearer \(bearerToken)")
  233. }
  234. /// Returns an `Authorization` header.
  235. ///
  236. /// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use
  237. /// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use
  238. /// `HTTPHeader.authorization(bearerToken:)`.
  239. ///
  240. /// - Parameter value: The `Authorization` value.
  241. ///
  242. /// - Returns: The header.
  243. public static func authorization(_ value: String) -> HTTPHeader {
  244. HTTPHeader(name: "Authorization", value: value)
  245. }
  246. /// Returns a `Content-Disposition` header.
  247. ///
  248. /// - Parameter value: The `Content-Disposition` value.
  249. ///
  250. /// - Returns: The header.
  251. public static func contentDisposition(_ value: String) -> HTTPHeader {
  252. HTTPHeader(name: "Content-Disposition", value: value)
  253. }
  254. /// Returns a `Content-Encoding` header.
  255. ///
  256. /// - Parameter value: The `Content-Encoding`.
  257. ///
  258. /// - Returns: The header.
  259. public static func contentEncoding(_ value: String) -> HTTPHeader {
  260. HTTPHeader(name: "Content-Encoding", value: value)
  261. }
  262. /// Returns a `Content-Type` header.
  263. ///
  264. /// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not
  265. /// be necessary to manually set this value.
  266. ///
  267. /// - Parameter value: The `Content-Type` value.
  268. ///
  269. /// - Returns: The header.
  270. public static func contentType(_ value: String) -> HTTPHeader {
  271. HTTPHeader(name: "Content-Type", value: value)
  272. }
  273. /// Returns a `User-Agent` header.
  274. ///
  275. /// - Parameter value: The `User-Agent` value.
  276. ///
  277. /// - Returns: The header.
  278. public static func userAgent(_ value: String) -> HTTPHeader {
  279. HTTPHeader(name: "User-Agent", value: value)
  280. }
  281. }
  282. extension Array where Element == HTTPHeader {
  283. /// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists.
  284. func index(of name: String) -> Int? {
  285. let lowercasedName = name.lowercased()
  286. return firstIndex { $0.name.lowercased() == lowercasedName }
  287. }
  288. }
  289. // MARK: - Defaults
  290. extension HTTPHeaders {
  291. /// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and
  292. /// `User-Agent`.
  293. public static let `default`: HTTPHeaders = [.defaultAcceptEncoding,
  294. .defaultAcceptLanguage,
  295. .defaultUserAgent]
  296. }
  297. extension HTTPHeader {
  298. /// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS
  299. /// versions.
  300. ///
  301. /// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) .
  302. public static let defaultAcceptEncoding: HTTPHeader = {
  303. let encodings: [String]
  304. if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) {
  305. encodings = ["br", "gzip", "deflate"]
  306. } else {
  307. encodings = ["gzip", "deflate"]
  308. }
  309. return .acceptEncoding(encodings.qualityEncoded())
  310. }()
  311. /// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's
  312. /// `preferredLanguages`.
  313. ///
  314. /// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5).
  315. public static let defaultAcceptLanguage: HTTPHeader = .acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded())
  316. /// Returns Alamofire's default `User-Agent` header.
  317. ///
  318. /// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3).
  319. ///
  320. /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0`
  321. public static let defaultUserAgent: HTTPHeader = {
  322. let info = Bundle.main.infoDictionary
  323. let executable = (info?["CFBundleExecutable"] as? String) ??
  324. (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ??
  325. "Unknown"
  326. let bundle = info?["CFBundleIdentifier"] as? String ?? "Unknown"
  327. let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown"
  328. let appBuild = info?["CFBundleVersion"] as? String ?? "Unknown"
  329. let osNameVersion: String = {
  330. let version = ProcessInfo.processInfo.operatingSystemVersion
  331. let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
  332. let osName: String = {
  333. #if os(iOS)
  334. #if targetEnvironment(macCatalyst)
  335. return "macOS(Catalyst)"
  336. #else
  337. return "iOS"
  338. #endif
  339. #elseif os(watchOS)
  340. return "watchOS"
  341. #elseif os(tvOS)
  342. return "tvOS"
  343. #elseif os(macOS)
  344. return "macOS"
  345. #elseif os(Linux)
  346. return "Linux"
  347. #elseif os(Windows)
  348. return "Windows"
  349. #elseif os(Android)
  350. return "Android"
  351. #else
  352. return "Unknown"
  353. #endif
  354. }()
  355. return "\(osName) \(versionString)"
  356. }()
  357. let alamofireVersion = "Alamofire/\(version)"
  358. let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
  359. return .userAgent(userAgent)
  360. }()
  361. }
  362. extension Collection where Element == String {
  363. func qualityEncoded() -> String {
  364. enumerated().map { index, encoding in
  365. let quality = 1.0 - (Double(index) * 0.1)
  366. return "\(encoding);q=\(quality)"
  367. }.joined(separator: ", ")
  368. }
  369. }
  370. // MARK: - System Type Extensions
  371. extension URLRequest {
  372. /// Returns `allHTTPHeaderFields` as `HTTPHeaders`.
  373. public var headers: HTTPHeaders {
  374. get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() }
  375. set { allHTTPHeaderFields = newValue.dictionary }
  376. }
  377. }
  378. extension HTTPURLResponse {
  379. /// Returns `allHeaderFields` as `HTTPHeaders`.
  380. public var headers: HTTPHeaders {
  381. (allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders()
  382. }
  383. }
  384. extension URLSessionConfiguration {
  385. /// Returns `httpAdditionalHeaders` as `HTTPHeaders`.
  386. public var headers: HTTPHeaders {
  387. get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() }
  388. set { httpAdditionalHeaders = newValue.dictionary }
  389. }
  390. }