1
0

HttpServer.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. //
  2. // HttpServer.swift
  3. // Swifter
  4. // Copyright (c) 2014 Damian Kołakowski. All rights reserved.
  5. //
  6. import Foundation
  7. public class HttpServer
  8. {
  9. static let VERSION = "1.0.2";
  10. public typealias Handler = HttpRequest -> HttpResponse
  11. var handlers: [(expression: NSRegularExpression, handler: Handler)] = []
  12. var clientSockets: Set<CInt> = []
  13. let clientSocketsLock = 0
  14. var acceptSocket: CInt = -1
  15. let matchingOptions = NSMatchingOptions(rawValue: 0)
  16. let expressionOptions = NSRegularExpressionOptions(rawValue: 0)
  17. public init() { }
  18. public subscript (path: String) -> Handler? {
  19. get {
  20. return nil
  21. }
  22. set {
  23. if let newHandler = newValue,
  24. let regex = try? NSRegularExpression(pattern: path, options: expressionOptions){
  25. handlers.append(expression: regex, handler: newHandler)
  26. }
  27. }
  28. }
  29. public func routes() -> [String] { return handlers.map { $0.0.pattern } }
  30. public func start(listenPort: in_port_t = 8080) throws {
  31. stop()
  32. do {
  33. let socket = try Socket.tcpForListen(listenPort)
  34. self.acceptSocket = socket
  35. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
  36. while let socket = try? Socket.acceptClientSocket(self.acceptSocket) {
  37. HttpServer.lock(self.clientSocketsLock) {
  38. self.clientSockets.insert(socket)
  39. }
  40. if self.acceptSocket == -1 { return }
  41. let socketAddress = try? Socket.peername(socket)!
  42. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
  43. let parser = HttpParser()
  44. while let request = try? parser.nextHttpRequest(socket) {
  45. let keepAlive = parser.supportsKeepAlive(request.headers)
  46. let response: HttpResponse
  47. if let (expression, handler) = self.findHandler(request.url) {
  48. let capturedUrlsGroups = self.captureExpressionGroups(expression, value: request.url)
  49. let updatedRequest = HttpRequest(url: request.url, urlParams: request.urlParams, method: request.method, headers: request.headers, body: request.body, capturedUrlGroups: capturedUrlsGroups, address: socketAddress)
  50. response = handler(updatedRequest)
  51. } else {
  52. response = HttpResponse.NotFound
  53. }
  54. HttpServer.respond(socket, response: response, keepAlive: keepAlive)
  55. if !keepAlive { break }
  56. }
  57. Socket.release(socket)
  58. HttpServer.lock(self.clientSocketsLock) {
  59. self.clientSockets.remove(socket)
  60. }
  61. }
  62. }
  63. self.stop()
  64. }
  65. } catch {
  66. throw error
  67. }
  68. }
  69. func findHandler(url:String) -> (NSRegularExpression, Handler)? {
  70. let u = NSURL(string: url)!
  71. let path = u.path!
  72. for handler in self.handlers {
  73. let regex = handler.0
  74. let matches = regex.numberOfMatchesInString(path, options: self.matchingOptions, range: HttpServer.asciiRange(path)) > 0
  75. if matches {
  76. return handler;
  77. }
  78. }
  79. return nil
  80. }
  81. func captureExpressionGroups(expression: NSRegularExpression, value: String) -> [String] {
  82. let u = NSURL(string: value)!
  83. let path = u.path!
  84. var capturedGroups = [String]()
  85. if let result = expression.firstMatchInString(path, options: matchingOptions, range: HttpServer.asciiRange(path)) {
  86. let nsValue: NSString = path
  87. for var i = 1 ; i < result.numberOfRanges ; ++i {
  88. if let group = nsValue.substringWithRange(result.rangeAtIndex(i)).stringByRemovingPercentEncoding {
  89. capturedGroups.append(group)
  90. }
  91. }
  92. }
  93. return capturedGroups
  94. }
  95. public func stop() {
  96. Socket.release(acceptSocket)
  97. acceptSocket = -1
  98. HttpServer.lock(self.clientSocketsLock) {
  99. for clientSocket in self.clientSockets {
  100. Socket.release(clientSocket)
  101. }
  102. self.clientSockets.removeAll(keepCapacity: true)
  103. }
  104. }
  105. public class func asciiRange(value: String) -> NSRange {
  106. return NSMakeRange(0, value.lengthOfBytesUsingEncoding(NSASCIIStringEncoding))
  107. }
  108. public class func lock(handle: AnyObject, closure: () -> ()) {
  109. objc_sync_enter(handle)
  110. closure()
  111. objc_sync_exit(handle)
  112. }
  113. public class func respond(socket: CInt, response: HttpResponse, keepAlive: Bool) {
  114. do {
  115. try Socket.writeUTF8(socket, string: "HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
  116. let length = response.body()?.length ?? 0
  117. try Socket.writeASCII(socket, string: "Content-Length: \(length)\r\n")
  118. if keepAlive {
  119. try Socket.writeASCII(socket, string: "Connection: keep-alive\r\n")
  120. }
  121. for (name, value) in response.headers() {
  122. try Socket.writeASCII(socket, string: "\(name): \(value)\r\n")
  123. }
  124. try Socket.writeASCII(socket, string: "\r\n")
  125. if let body = response.body() {
  126. try Socket.writeData(socket, data: body)
  127. }
  128. } catch {
  129. // TODO: handle error
  130. }
  131. }
  132. }