1
0

HttpRequest.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. //
  2. // HttpRequest.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. #if os(Linux)
  8. import Glibc
  9. #else
  10. import Foundation
  11. #endif
  12. public class HttpRequest {
  13. public var path: String = ""
  14. public var queryParams: [(String, String)] = []
  15. public var method: String = ""
  16. public var headers: [String: String] = [:]
  17. public var body: [UInt8] = []
  18. public var address: String? = ""
  19. public var params: [String: String] = [:]
  20. public func hasTokenForHeader(headerName: String, token: String) -> Bool {
  21. guard let headerValue = headers[headerName] else {
  22. return false
  23. }
  24. return headerValue.split(",").filter({ $0.trim().lowercaseString == token }).count > 0
  25. }
  26. public func parseUrlencodedForm() -> [(String, String)] {
  27. guard let contentTypeHeader = headers["content-type"] else {
  28. return []
  29. }
  30. let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
  31. guard let contentType = contentTypeHeaderTokens.first where contentType == "application/x-www-form-urlencoded" else {
  32. return []
  33. }
  34. return String.fromUInt8(body).split("&").map { param -> (String, String) in
  35. let tokens = param.split("=")
  36. if let name = tokens.first, value = tokens.last where tokens.count == 2 {
  37. return (name.replace("+", " ").removePercentEncoding(),
  38. value.replace("+", " ").removePercentEncoding())
  39. }
  40. return ("","")
  41. }
  42. }
  43. public struct MultiPart {
  44. public let headers: [String: String]
  45. public let body: [UInt8]
  46. public var name: String? {
  47. return valueFor("content-disposition", parameter: "name")?.unquote()
  48. }
  49. public var fileName: String? {
  50. return valueFor("content-disposition", parameter: "filename")?.unquote()
  51. }
  52. private func valueFor(headerName: String, parameter: String) -> String? {
  53. return headers.reduce([String]()) { (combined, header: (key: String, value: String)) -> [String] in
  54. guard header.key == headerName else {
  55. return combined
  56. }
  57. let headerValueParams = header.value.split(";").map { $0.trim() }
  58. return headerValueParams.reduce(combined, combine: { (results, token) -> [String] in
  59. let parameterTokens = token.split(1, separator: "=")
  60. if parameterTokens.first == parameter, let value = parameterTokens.last {
  61. return results + [value]
  62. }
  63. return results
  64. })
  65. }.first
  66. }
  67. }
  68. public func parseMultiPartFormData() -> [MultiPart] {
  69. guard let contentTypeHeader = headers["content-type"] else {
  70. return []
  71. }
  72. let contentTypeHeaderTokens = contentTypeHeader.split(";").map { $0.trim() }
  73. guard let contentType = contentTypeHeaderTokens.first where contentType == "multipart/form-data" else {
  74. return []
  75. }
  76. var boundary: String? = nil
  77. contentTypeHeaderTokens.forEach({
  78. let tokens = $0.split("=")
  79. if let key = tokens.first where key == "boundary" && tokens.count == 2 {
  80. boundary = tokens.last
  81. }
  82. })
  83. if let boundary = boundary where boundary.utf8.count > 0 {
  84. return parseMultiPartFormData(body, boundary: "--\(boundary)")
  85. }
  86. return []
  87. }
  88. private func parseMultiPartFormData(data: [UInt8], boundary: String) -> [MultiPart] {
  89. var generator = data.generate()
  90. var result = [MultiPart]()
  91. while let part = nextMultiPart(&generator, boundary: boundary, isFirst: result.isEmpty) {
  92. result.append(part)
  93. }
  94. return result
  95. }
  96. private func nextMultiPart(inout generator: IndexingGenerator<[UInt8]>, boundary: String, isFirst: Bool) -> MultiPart? {
  97. if isFirst {
  98. guard nextMultiPartLine(&generator) == boundary else {
  99. return nil
  100. }
  101. } else {
  102. nextMultiPartLine(&generator)
  103. }
  104. var headers = [String: String]()
  105. while let line = nextMultiPartLine(&generator) where !line.isEmpty {
  106. let tokens = line.split(":")
  107. if let name = tokens.first, value = tokens.last where tokens.count == 2 {
  108. headers[name.lowercaseString] = value.trim()
  109. }
  110. }
  111. guard let body = nextMultiPartBody(&generator, boundary: boundary) else {
  112. return nil
  113. }
  114. return MultiPart(headers: headers, body: body)
  115. }
  116. private func nextMultiPartLine(inout generator: IndexingGenerator<[UInt8]>) -> String? {
  117. var result = String()
  118. while let value = generator.next() {
  119. if value > HttpRequest.CR {
  120. result.append(Character(UnicodeScalar(value)))
  121. }
  122. if value == HttpRequest.NL {
  123. break
  124. }
  125. }
  126. return result
  127. }
  128. static let CR = UInt8(13)
  129. static let NL = UInt8(10)
  130. private func nextMultiPartBody(inout generator: IndexingGenerator<[UInt8]>, boundary: String) -> [UInt8]? {
  131. var body = [UInt8]()
  132. let boundaryArray = [UInt8](boundary.utf8)
  133. var matchOffset = 0;
  134. while let x = generator.next() {
  135. matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
  136. body.append(x)
  137. if matchOffset == boundaryArray.count {
  138. body.removeRange(Range<Int>(body.count-matchOffset ..< body.count))
  139. if body.last == HttpRequest.NL {
  140. body.removeLast()
  141. if body.last == HttpRequest.CR {
  142. body.removeLast()
  143. }
  144. }
  145. return body
  146. }
  147. }
  148. return nil
  149. }
  150. }