1
0

HttpRequest.swift 5.7 KB

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