forked from PerfectlySoft/Perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastCGIServer.swift
More file actions
240 lines (191 loc) · 6.09 KB
/
Copy pathFastCGIServer.swift
File metadata and controls
240 lines (191 loc) · 6.09 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
// FastCGIServer.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/6/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
#else
import Darwin
#endif
/// A server for the FastCGI protocol.
/// Listens for requests on either a named pipe or a TCP socket. Once started, it does not stop or return outside of a catastrophic error.
/// When a request is received, the server will instantiate a `WebRequest`/`WebResponse` pair and they will handle the remainder of the request.
public class FastCGIServer {
private var net: NetTCP?
/// Empty public initializer
public init() {
}
/// Start the server on the indicated named pipe
public func start(namedPipe: String) throws {
if access(namedPipe, F_OK) != -1 {
// exists. remove it
unlink(namedPipe)
}
let pipe = NetNamedPipe()
pipe.initSocket()
try pipe.bind(namedPipe)
pipe.listen()
chmod(namedPipe, mode_t(S_IRWXU|S_IRWXO|S_IRWXG))
self.net = pipe
defer { pipe.close() }
print("Starting FastCGI server on named pipe "+namedPipe)
self.start()
}
/// Start the server on the indicated TCP port and optional address
public func start(port: UInt16, bindAddress: String = "0.0.0.0") throws {
let socket = NetTCP()
socket.initSocket()
try socket.bind(port, address: bindAddress)
socket.listen()
defer { socket.close() }
print("Starting FastCGi server on \(bindAddress):\(port)")
self.start()
}
func start() {
if let n = self.net {
n.forEachAccept {
[weak self] (net: NetTCP?) -> () in
if let n = net {
Threading.dispatchBlock {
self?.handleConnection(n)
}
}
}
}
}
func handleConnection(net: NetTCP) {
let fcgiReq = FastCGIRequest(net: net)
readRecord(fcgiReq)
}
func readRecord(fcgiReq: FastCGIRequest) {
fcgiReq.readRecord {
[weak self] (r:FastCGIRecord?) -> () in
guard let record = r else {
fcgiReq.connection.close()
return // died. timed out. errorered
}
self?.handleRecord(fcgiReq, fcgiRecord: record)
}
}
func handleRecord(fcgiReq: FastCGIRequest, fcgiRecord: FastCGIRecord) {
switch fcgiRecord.recType {
case fcgiBeginRequest:
// FastCGIBeginRequestBody UInt16 role, UInt8 flags
let role: UInt16 = ntohs((UInt16(fcgiRecord.content![1]) << 8) | UInt16(fcgiRecord.content![0]))
let flags: UInt8 = fcgiRecord.content![2]
fcgiReq.requestParams["L_FCGI_ROLE"] = String(role)
fcgiReq.requestParams["L_FCGI_FLAGS"] = String(flags)
fcgiReq.requestId = fcgiRecord.requestId
case fcgiParams:
if fcgiRecord.contentLength > 0 {
let bytes = fcgiRecord.content!
var idx = 0
repeat {
// sizes are either one byte or 4
var sz = Int32(bytes[idx])
idx += 1
if (sz & 0x80) != 0 { // name length
sz = (sz & 0x7f) << 24
sz += (Int32(bytes[idx]) << 16)
idx += 1
sz += (Int32(bytes[idx]) << 8)
idx += 1
sz += Int32(bytes[idx])
idx += 1
}
var vsz = Int32(bytes[idx])
idx += 1
if (vsz & 0x80) != 0 { // value length
vsz = (vsz & 0x7f) << 24
vsz += (Int32(bytes[idx]) << 16)
idx += 1
vsz += (Int32(bytes[idx]) << 8)
idx += 1
vsz += Int32(bytes[idx])
idx += 1
}
if sz > 0 {
let idx2 = Int(idx + sz)
let name = UTF8Encoding.encode(bytes[idx..<idx2])
let idx3 = idx2 + Int(vsz)
let value = UTF8Encoding.encode(bytes[idx2..<idx3])
fcgiReq.requestParams[name] = value
idx = idx3
}
} while idx < bytes.count
}
case fcgiStdin:
if fcgiRecord.contentLength > 0 {
fcgiReq.putStdinData(fcgiRecord.content!)
} else { // done initiating the request. run with it
runRequest(fcgiReq)
return
}
case fcgiData:
if fcgiRecord.contentLength > 0 {
fcgiReq.requestParams["L_FCGI_DATA"] = UTF8Encoding.encode(fcgiRecord.content!)
}
case fcgiXStdin:
if Int(fcgiRecord.contentLength) == sizeof(UInt32) {
let one = UInt32(fcgiRecord.content![0])
let two = UInt32(fcgiRecord.content![1])
let three = UInt32(fcgiRecord.content![2])
let four = UInt32(fcgiRecord.content![3])
let size = ntohl((four << 24) + (three << 16) + (two << 8) + one)
readXStdin(fcgiReq, size: Int(size))
return
}
default:
print("Unhandled FastCGI record type \(fcgiRecord.recType)")
}
fcgiReq.lastRecordType = fcgiRecord.recType
readRecord(fcgiReq)
}
func readXStdin(fcgiReq: FastCGIRequest, size: Int) {
fcgiReq.connection.readSomeBytes(size) {
[weak self] (b:[UInt8]?) -> () in
guard let bytes = b else {
fcgiReq.connection.close()
return // died. timed out. errorered
}
fcgiReq.putStdinData(bytes)
let remaining = size - bytes.count
if remaining == 0 {
fcgiReq.lastRecordType = fcgiStdin
self?.readRecord(fcgiReq)
} else {
self?.readXStdin(fcgiReq, size: remaining)
}
}
}
func runRequest(fcgiReq: FastCGIRequest) {
let request = WebRequest(fcgiReq)
let response = WebResponse(fcgiReq, request: request)
response.respond {
let status = response.appStatus
let finalBytes = fcgiReq.makeEndRequestBody(Int(fcgiReq.requestId), appStatus: status, protocolStatus: fcgiRequestComplete)
fcgiReq.writeBytes(finalBytes)
fcgiReq.connection.close()
}
}
}