HttpRequest.swift 5.7 KB

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