HttpServer.swift 5.7 KB

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