-
Notifications
You must be signed in to change notification settings - Fork 540
/
HttpServerIO.swift
203 lines (165 loc) · 6.44 KB
/
HttpServerIO.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
import Dispatch
public protocol HttpServerIODelegate: class {
func socketConnectionReceived(_ socket: Socket)
}
public class HttpServerIO {
public weak var delegate: HttpServerIODelegate?
private var socket = Socket(socketFileDescriptor: -1)
private var sockets = Set<Socket>()
public enum HttpServerIOState: Int32 {
case starting
case running
case stopping
case stopped
}
private var stateValue: Int32 = HttpServerIOState.stopped.rawValue
public private(set) var state: HttpServerIOState {
get {
return HttpServerIOState(rawValue: stateValue)!
}
set(state) {
#if !os(Linux)
OSAtomicCompareAndSwapInt(self.state.rawValue, state.rawValue, &stateValue)
#else
self.stateValue = state.rawValue
#endif
}
}
public var operating: Bool { return self.state == .running }
/// String representation of the IPv4 address to receive requests from.
/// It's only used when the server is started with `forceIPv4` option set to true.
/// Otherwise, `listenAddressIPv6` will be used.
public var listenAddressIPv4: String?
/// String representation of the IPv6 address to receive requests from.
/// It's only used when the server is started with `forceIPv4` option set to false.
/// Otherwise, `listenAddressIPv4` will be used.
public var listenAddressIPv6: String?
private let queue = DispatchQueue(label: "swifter.httpserverio.clientsockets")
public func port() throws -> Int {
return Int(try socket.port())
}
public func isIPv4() throws -> Bool {
return try socket.isIPv4()
}
deinit {
stop()
}
@available(macOS 10.10, *)
public func start(_ port: in_port_t = 8080, forceIPv4: Bool = false, priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.background) throws {
guard !self.operating else { return }
stop()
self.state = .starting
let address = forceIPv4 ? listenAddressIPv4 : listenAddressIPv6
self.socket = try Socket.tcpSocketForListen(port, forceIPv4, SOMAXCONN, address)
self.state = .running
DispatchQueue.global(qos: priority).async { [weak self] in
guard let strongSelf = self else { return }
guard strongSelf.operating else { return }
while let socket = try? strongSelf.socket.acceptClientSocket() {
DispatchQueue.global(qos: priority).async { [weak self] in
guard let strongSelf = self else { return }
guard strongSelf.operating else { return }
strongSelf.queue.async {
strongSelf.sockets.insert(socket)
}
strongSelf.handleConnection(socket)
strongSelf.queue.async {
strongSelf.sockets.remove(socket)
}
}
}
strongSelf.stop()
}
}
public func stop() {
guard self.operating else { return }
self.state = .stopping
// Shutdown connected peers because they can live in 'keep-alive' or 'websocket' loops.
for socket in self.sockets {
socket.close()
}
self.queue.sync {
self.sockets.removeAll(keepingCapacity: true)
}
socket.close()
self.state = .stopped
}
public func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
return ([:], { _ in HttpResponse.notFound })
}
private func handleConnection(_ socket: Socket) {
let parser = HttpParser()
while self.operating, let request = try? parser.readHttpRequest(socket) {
let request = request
request.address = try? socket.peername()
let (params, handler) = self.dispatch(request)
request.params = params
let response = handler(request)
var keepConnection = parser.supportsKeepAlive(request.headers)
do {
if self.operating {
keepConnection = try self.respond(socket, response: response, keepAlive: keepConnection)
}
} catch {
print("Failed to send response: \(error)")
break
}
if let session = response.socketSession() {
delegate?.socketConnectionReceived(socket)
session(socket)
break
}
if !keepConnection { break }
}
socket.close()
}
private struct InnerWriteContext: HttpResponseBodyWriter {
let socket: Socket
func write(_ file: String.File) throws {
try socket.writeFile(file)
}
func write(_ data: [UInt8]) throws {
try write(ArraySlice(data))
}
func write(_ data: ArraySlice<UInt8>) throws {
try socket.writeUInt8(data)
}
func write(_ data: NSData) throws {
try socket.writeData(data)
}
func write(_ data: Data) throws {
try socket.writeData(data)
}
}
private func respond(_ socket: Socket, response: HttpResponse, keepAlive: Bool) throws -> Bool {
guard self.operating else { return false }
// Some web-socket clients (like Jetfire) expects to have header section in a single packet.
// We can't promise that but make sure we invoke "write" only once for response header section.
var responseHeader = String()
responseHeader.append("HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
let content = response.content()
if content.length >= 0 {
responseHeader.append("Content-Length: \(content.length)\r\n")
}
if keepAlive && content.length != -1 {
responseHeader.append("Connection: keep-alive\r\n")
}
for (name, value) in response.headers() {
responseHeader.append("\(name): \(value)\r\n")
}
responseHeader.append("\r\n")
try socket.writeUTF8(responseHeader)
if let writeClosure = content.write {
let context = InnerWriteContext(socket: socket)
try writeClosure(context)
}
return keepAlive && content.length != -1
}
}