Http.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. //
  2. // Http.swift
  3. // Swifter
  4. //
  5. // Copyright © 2016 kolakowski. All rights reserved.
  6. //
  7. import Foundation
  8. open class Request {
  9. public enum HttpVersion { case http10, http11 }
  10. public var httpVersion = HttpVersion.http10
  11. public var method = ""
  12. public var path = ""
  13. public var query = [(String, String)]()
  14. public var headers = [(String, String)]()
  15. public var body = [UInt8]()
  16. public var contentLength = 0
  17. }
  18. open class Response {
  19. public init() { }
  20. public init(_ status: Status = Status.ok) {
  21. self.status = status.rawValue
  22. }
  23. public init(_ status: Int = Status.ok.rawValue) {
  24. self.status = status
  25. }
  26. public init(_ body: Array<UInt8>) {
  27. self.body.append(contentsOf: body)
  28. }
  29. public init(_ body: ArraySlice<UInt8>) {
  30. self.body.append(contentsOf: body)
  31. }
  32. public var status = Status.ok.rawValue
  33. public var headers = [(String, String)]()
  34. public var body = [UInt8]()
  35. public var processingSuccesor: IncomingDataProcessor? = nil
  36. }
  37. public class TextResponse: Response {
  38. public init(_ status: Int = Status.ok.rawValue, _ text: String) {
  39. super.init(status)
  40. self.headers.append(("Content-Type", "text/plain"))
  41. self.body = [UInt8](text.utf8)
  42. }
  43. }
  44. public enum Status: Int {
  45. case `continue` = 100
  46. case switchingProtocols = 101
  47. case ok = 200
  48. case created = 201
  49. case accepted = 202
  50. case noContent = 204
  51. case resetContent = 205
  52. case partialContent = 206
  53. case movedPerm = 301
  54. case notModified = 304
  55. case badRequest = 400
  56. case unauthorized = 401
  57. case forbidden = 403
  58. case notFound = 404
  59. case internalServerError = 500
  60. }
  61. public class HttpIncomingDataPorcessor: Hashable, IncomingDataProcessor {
  62. private enum State {
  63. case waitingForHeaders
  64. case waitingForBody
  65. }
  66. private var state = State.waitingForHeaders
  67. private let socket: Int32
  68. private var buffer = Array<UInt8>()
  69. private var request = Request()
  70. private let callback: ((Request) throws -> Void)
  71. public init(_ socket: Int32, _ closure: @escaping ((Request) throws -> Void)) {
  72. self.socket = socket
  73. self.callback = closure
  74. }
  75. public static func == (lhs: HttpIncomingDataPorcessor, rhs: HttpIncomingDataPorcessor) -> Bool {
  76. return lhs.socket == rhs.socket
  77. }
  78. public var hashValue: Int { return Int(self.socket) }
  79. public func process(_ chunk: ArraySlice<UInt8>) throws {
  80. switch self.state {
  81. case .waitingForHeaders:
  82. guard self.buffer.count + chunk.count < 4096 else {
  83. throw SwifterError.parse("Headers size exceeds the limit.")
  84. }
  85. var iterator = chunk.makeIterator()
  86. while let byte = iterator.next() {
  87. if byte != UInt8.cr {
  88. buffer.append(byte)
  89. }
  90. if buffer.count >= 2 && buffer[buffer.count-1] == UInt8.lf && buffer[buffer.count-2] == UInt8.lf {
  91. self.buffer.removeLast(2)
  92. self.request = try self.consumeHeader(buffer)
  93. self.buffer.removeAll(keepingCapacity: true)
  94. let left = [UInt8](iterator)
  95. self.state = .waitingForBody
  96. try self.process(left[0..<left.count])
  97. break
  98. }
  99. }
  100. case .waitingForBody:
  101. guard self.request.body.count + chunk.count <= request.contentLength else {
  102. throw SwifterError.parse("Peer sent more data then required ('Content-Length' = \(request.contentLength).")
  103. }
  104. request.body.append(contentsOf: chunk)
  105. if request.body.count == request.contentLength {
  106. self.state = .waitingForHeaders
  107. try self.callback(request)
  108. }
  109. }
  110. }
  111. private func consumeHeader(_ data: [UInt8]) throws -> Request {
  112. let lines = data.split(separator: UInt8.lf)
  113. guard let requestLine = lines.first else {
  114. throw SwifterError.httpError("No status line.")
  115. }
  116. let requestLineTokens = requestLine.split(separator: UInt8.space)
  117. guard requestLineTokens.count >= 3 else {
  118. throw SwifterError.httpError("Invalid status line.")
  119. }
  120. let request = Request()
  121. if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30] {
  122. request.httpVersion = .http10
  123. } else if requestLineTokens[2] == [0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31] {
  124. request.httpVersion = .http11
  125. } else {
  126. throw SwifterError.parse("Invalid http version: \(requestLineTokens[2])")
  127. }
  128. request.headers = lines
  129. .dropFirst()
  130. .map { line in
  131. let headerTokens = line.split(separator: UInt8.colon, maxSplits: 1)
  132. if let name = headerTokens.first, let value = headerTokens.last {
  133. if let nameString = String(bytes: name, encoding: String.Encoding.ascii),
  134. let valueString = String(bytes: value, encoding: String.Encoding.ascii) {
  135. return (nameString.lowercased(), valueString.trimmingCharacters(in: CharacterSet.whitespaces))
  136. }
  137. }
  138. return ("", "")
  139. }
  140. if let (_, value) = request.headers
  141. .filter({ $0.0 == "content-length" })
  142. .first {
  143. guard let contentLength = Int(value) else {
  144. throw SwifterError.parse("Invalid 'Content-Length' header value \(value).")
  145. }
  146. request.contentLength = contentLength
  147. }
  148. guard let method = String(bytes: requestLineTokens[0], encoding: .ascii) else {
  149. throw SwifterError.parse("Invalid 'method' value \(requestLineTokens[0]).")
  150. }
  151. request.method = method
  152. guard let path = String(bytes: requestLineTokens[1], encoding: .ascii) else {
  153. throw SwifterError.parse("Invalid 'path' value \(requestLineTokens[1]).")
  154. }
  155. let queryComponents = path.components(separatedBy: "?")
  156. if queryComponents.count > 1, let first = queryComponents.first, let last = queryComponents.last {
  157. request.path = first
  158. request.query = last
  159. .components(separatedBy: "&")
  160. .reduce([(String, String)]()) { (c, s) -> [(String, String)] in
  161. let tokens = s.components(separatedBy: "=")
  162. if let name = tokens.first, let value = tokens.last {
  163. if let nameDecoded = name.removingPercentEncoding, let valueDecoded = value.removingPercentEncoding {
  164. return c + [(nameDecoded, tokens.count > 1 ? valueDecoded : "")]
  165. }
  166. }
  167. return c
  168. }
  169. } else {
  170. request.path = path
  171. }
  172. return request
  173. }
  174. }