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. }
  30. }
  31. }
  32. public func routes() -> [String] { return handlers.map { $0.0.pattern } }
  33. public func start(listenPort: in_port_t = 8080, error: NSErrorPointer = nil) -> Bool {
  34. stop()
  35. if let socket = Socket.tcpForListen(listenPort, error: error) {
  36. self.acceptSocket = socket
  37. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
  38. while let socket = Socket.acceptClientSocket(self.acceptSocket) {
  39. HttpServer.lock(self.clientSocketsLock) {
  40. self.clientSockets.insert(socket)
  41. }
  42. if self.acceptSocket == -1 { return }
  43. let socketAddress = Socket.peername(socket)
  44. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
  45. let parser = HttpParser()
  46. while let request = parser.nextHttpRequest(socket) {
  47. let keepAlive = parser.supportsKeepAlive(request.headers)
  48. if let (expression, handler) = self.findHandler(request.url) {
  49. let capturedUrlsGroups = self.captureExpressionGroups(expression, value: request.url)
  50. let updatedRequest = HttpRequest(url: request.url, urlParams: request.urlParams, method: request.method, headers: request.headers, body: request.body, capturedUrlGroups: capturedUrlsGroups, address: socketAddress)
  51. HttpServer.respond(socket, response: handler(updatedRequest), keepAlive: keepAlive)
  52. } else {
  53. HttpServer.respond(socket, response: HttpResponse.NotFound, keepAlive: keepAlive)
  54. }
  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. return true
  66. }
  67. return false
  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. Socket.writeUTF8(socket, string: "HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
  115. if let body = response.body() {
  116. Socket.writeASCII(socket, string: "Content-Length: \(body.length)\r\n")
  117. } else {
  118. Socket.writeASCII(socket, string: "Content-Length: 0\r\n")
  119. }
  120. if keepAlive {
  121. Socket.writeASCII(socket, string: "Connection: keep-alive\r\n")
  122. }
  123. for (name, value) in response.headers() {
  124. Socket.writeASCII(socket, string: "\(name): \(value)\r\n")
  125. }
  126. Socket.writeASCII(socket, string: "\r\n")
  127. if let body = response.body() {
  128. Socket.writeData(socket, data: body)
  129. }
  130. }
  131. }