1
0

HttpParser.swift 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // HttpParser.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. enum HttpParserError: Error {
  9. case InvalidStatusLine(String)
  10. }
  11. public class HttpParser {
  12. public init() { }
  13. public func readHttpRequest(_ socket: Socket) throws -> HttpRequest {
  14. let statusLine = try socket.readLine()
  15. let statusLineTokens = statusLine.components(separatedBy: " ")
  16. if statusLineTokens.count < 3 {
  17. throw HttpParserError.InvalidStatusLine(statusLine)
  18. }
  19. let request = HttpRequest()
  20. request.method = statusLineTokens[0]
  21. request.path = statusLineTokens[1]
  22. request.queryParams = extractQueryParams(request.path)
  23. request.headers = try readHeaders(socket)
  24. if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) {
  25. request.body = try readBody(socket, size: contentLengthValue)
  26. }
  27. return request
  28. }
  29. private func extractQueryParams(_ url: String) -> [(String, String)] {
  30. guard let questionMark = url.index(of: "?") else {
  31. return []
  32. }
  33. let queryStart = url.index(after: questionMark)
  34. guard url.endIndex > queryStart else { return [] }
  35. #if swift(>=4.0)
  36. let query = String(url[queryStart..<url.endIndex])
  37. #else
  38. guard let query = String(url[queryStart..<url.endIndex]) else { return [] }
  39. #endif
  40. return query.components(separatedBy: "&")
  41. .reduce([(String, String)]()) { (c, s) -> [(String, String)] in
  42. guard let nameEndIndex = s.index(of: "=") else {
  43. return c
  44. }
  45. guard let name = String(s[s.startIndex..<nameEndIndex]).removingPercentEncoding else {
  46. return c
  47. }
  48. let valueStartIndex = s.index(nameEndIndex, offsetBy: 1)
  49. guard valueStartIndex < s.endIndex else {
  50. return c + [(name, "")]
  51. }
  52. guard let value = String(s[valueStartIndex..<s.endIndex]).removingPercentEncoding else {
  53. return c + [(name, "")]
  54. }
  55. return c + [(name, value)]
  56. }
  57. }
  58. private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] {
  59. var body = [UInt8]()
  60. for _ in 0..<size { body.append(try socket.read()) }
  61. return body
  62. }
  63. private func readHeaders(_ socket: Socket) throws -> [String: String] {
  64. var headers = [String: String]()
  65. while case let headerLine = try socket.readLine() , !headerLine.isEmpty {
  66. let headerTokens = headerLine.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true).map(String.init)
  67. if let name = headerTokens.first, let value = headerTokens.last {
  68. headers[name.lowercased()] = value.trimmingCharacters(in: .whitespaces)
  69. }
  70. }
  71. return headers
  72. }
  73. func supportsKeepAlive(_ headers: [String: String]) -> Bool {
  74. if let value = headers["connection"] {
  75. return "keep-alive" == value.trimmingCharacters(in: .whitespaces)
  76. }
  77. return false
  78. }
  79. }