HttpParser.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. //
  2. // HttpParser.swift
  3. //
  4. // Created by Damian Kolakowski on 05/06/14.
  5. // Copyright (c) 2014 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. class HttpParser {
  9. class func err(reason:String) -> NSError {
  10. return NSError(domain: "HTTP_PARSER", code: 0, userInfo:[NSLocalizedFailureReasonErrorKey : reason])
  11. }
  12. func nextHttpRequest(socket: CInt, error:NSErrorPointer = nil) -> HttpRequest? {
  13. if let statusLine = nextLine(socket, error: error) {
  14. let statusTokens = split(statusLine, { $0 == " " })
  15. println(statusTokens)
  16. if ( statusTokens.count < 3 ) {
  17. if error != nil { error.memory = HttpParser.err("Invalid status line: \(statusLine)") }
  18. return nil
  19. }
  20. let method = statusTokens[0]
  21. let path = statusTokens[1]
  22. let urlParams = extractUrlParams(path)
  23. // TODO extract query parameters
  24. if let headers = nextHeaders(socket, error: error) {
  25. // TODO detect content-type and handle:
  26. // 'application/x-www-form-urlencoded' -> Dictionary
  27. // 'multipart' -> Dictionary
  28. if let contentSize = headers["content-length"]?.toInt() {
  29. let body = nextBody(socket, size: contentSize, error: error)
  30. return HttpRequest(url: path, urlParams: urlParams, method: method, headers: headers, body: body, capturedUrlGroups: [])
  31. }
  32. return HttpRequest(url: path, urlParams: urlParams, method: method, headers: headers, body: nil, capturedUrlGroups: [])
  33. }
  34. }
  35. return nil
  36. }
  37. private func extractUrlParams(url: String) -> [(String, String)] {
  38. var result = [(String, String)]()
  39. let tokens = url.componentsSeparatedByString("?")
  40. if tokens.count >= 2 {
  41. for pair in tokens[1].componentsSeparatedByString("&") {
  42. let keyAndValue = pair.componentsSeparatedByString("=")
  43. if keyAndValue.count >= 2 {
  44. result.append((keyAndValue[0], keyAndValue[1]))
  45. }
  46. }
  47. }
  48. return result
  49. }
  50. private func nextBody(socket: CInt, size: Int , error:NSErrorPointer) -> String? {
  51. var body = ""
  52. var counter = 0;
  53. while ( counter < size ) {
  54. let c = nextUInt8(socket)
  55. if ( c < 0 ) {
  56. if error != nil { error.memory = HttpParser.err("IO error while reading body") }
  57. return nil
  58. }
  59. body.append(UnicodeScalar(c))
  60. counter++;
  61. }
  62. return body
  63. }
  64. private func nextHeaders(socket: CInt, error:NSErrorPointer) -> Dictionary<String, String>? {
  65. var headers = Dictionary<String, String>()
  66. while let headerLine = nextLine(socket, error: error) {
  67. if ( headerLine.isEmpty ) {
  68. return headers
  69. }
  70. let headerTokens = split(headerLine, { $0 == ":" })
  71. if ( headerTokens.count >= 2 ) {
  72. // RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", paragraph 4.2, "Message Headers":
  73. // "Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive."
  74. // We can keep lower case version.
  75. let headerName = headerTokens[0].lowercaseString
  76. let headerValue = headerTokens[1].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  77. if ( !headerName.isEmpty && !headerValue.isEmpty ) {
  78. headers.updateValue(headerValue, forKey: headerName)
  79. }
  80. }
  81. }
  82. return nil
  83. }
  84. private func nextUInt8(socket: CInt) -> Int {
  85. var buffer = [UInt8](count: 1, repeatedValue: 0);
  86. let next = recv(socket, &buffer, UInt(buffer.count), 0)
  87. if next <= 0 { return next }
  88. return Int(buffer[0])
  89. }
  90. private func nextLine(socket: CInt, error:NSErrorPointer) -> String? {
  91. var characters: String = ""
  92. var n = 0
  93. do {
  94. n = nextUInt8(socket)
  95. if ( n > 13 /* CR */ ) { characters.append(Character(UnicodeScalar(n))) }
  96. } while ( n > 0 && n != 10 /* NL */)
  97. if ( n == -1 && characters.isEmpty ) {
  98. if error != nil { error.memory = Socket.socketLastError("recv(...) failed.") }
  99. return nil
  100. }
  101. return characters
  102. }
  103. func supportsKeepAlive(headers: Dictionary<String, String>) -> Bool {
  104. if let value = headers["connection"] {
  105. return "keep-alive" == value.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).lowercaseString
  106. }
  107. return false
  108. }
  109. }