-
Notifications
You must be signed in to change notification settings - Fork 0
/
shs.lua
361 lines (308 loc) · 10.7 KB
/
shs.lua
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
--- Adapted from https://gist.github.com/daurnimator/192dc5b210718dd129cfc1e5986df97b
local asserts = assert
local iiter = ipairs
local try = pcall
local setm = setmetatable
local to_n = tonumber
local to_s = tostring
local typ = type
local openf = io.open
local stderr = io.stderr
local write = io.write
local date = os.date
local insert = table.insert
local fmt = string.format
local ce = require "cqueues.errno"
local new_headers = require "http.headers".new
local server = require "http.server"
local http_tls = require "http.tls"
local http_util = require "http.util"
local zlib = require "http.zlib"
local Pkey = require "openssl.pkey"
local openssl_ssl = require "openssl.ssl"
local openssl_ctx = require "openssl.ssl.context"
local Crt = require "openssl.x509"
local Chain = require"openssl.x509.chain"
local query_args = http_util.query_args
local TEXT = "text/plain; charset=UTF-8"
--luacheck: ignore 111
local _ENV = {}
-- required for TLS context creation.
local function alpn_select(ssl, protos, version)
for _, proto in iiter(protos) do
if proto == "h2" and (version == nil or version == 2) then
-- HTTP2 only allows >= TLSv1.2
-- allow override via version
if ssl:getVersion() >= openssl_ssl.TLS1_2_VERSION or version == 2 then
return proto
end
elseif (proto == "http/1.1" and (version == nil or version == 1.1))
or (proto == "http/1.0" and (version == nil or version == 1.0)) then
return proto
end
end
return nil
end
-- takes a file of one of more PEM encoded certificates and splits them into a primary cert and a chain of intermediates.
local function decode_fullchain(crtfile, iscontent)
local crttxt
if iscontent then crttxt = crtfile else
local crtf = asserts(openf(crtfile, "r"))
crttxt = crtf:read"a"
crtf:close()
end
local crts, pos = {}, 1
repeat
local st, ed = crttxt:find("-----BEGIN CERTIFICATE-----", pos, true)
if st then
local st2, ed2 = crttxt:find("-----END CERTIFICATE-----", ed + 1, true)
if st2 then
insert(crts, crttxt:sub(st, ed2))
pos = ed2+1
end
end
until st == nil
local chain = Chain.new()
local primary = asserts(Crt.new(crts[1]))
for i = 2, #crts do
local crt = asserts(Crt.new(crts[i]))
chain:add(crt)
end
return primary,chain
end
-- construct a openssl context using the user's crtfile and keyfile.
local function new_ctx(version, crtpath, keypath)
local ctx = http_tls.new_server_context()
if http_tls.has_alpn then
ctx:setAlpnSelect(alpn_select, version)
end
if version == 2 then
ctx:setOptions(openssl_ctx.OP_NO_TLSv1 + openssl_ctx.OP_NO_TLSv1_1)
end
local keyfile = asserts(openf(keypath, "r"))
local primary,crt = decode_fullchain(crtpath)
asserts(ctx:setPrivateKey(Pkey.new(keyfile:read"a")))
asserts(ctx:setCertificate(primary))
asserts(ctx:setCertificateChain(crt))
keyfile:close()
return ctx
end
-- construct a openssl context using the user's crtfile and keyfile.
local function new_ctxlit(options)
local version = options.version or 1.1
local ctx = http_tls.new_server_context()
if http_tls.has_alpn then
ctx:setAlpnSelect(alpn_select, version)
end
if version == 2 then
ctx:setOptions(openssl_ctx.OP_NO_TLSv1 + openssl_ctx.OP_NO_TLSv1_1)
end
local primary,crt = decode_fullchain(options.crt, true)
asserts(ctx:setPrivateKey(Pkey.new(options.pkey)))
asserts(ctx:setCertificate(primary))
asserts(ctx:setCertificateChain(crt))
return ctx
end
local response_methods = {}
local response_mt = {
__index = response_methods;
__name = nil;
}
local function new_response(request_headers, stream, data, mtover)
local headers = new_headers();
headers:append(":status", "500")
local _, peer = stream:peername()
local fullpath = request_headers:get":path"
local query, path, fragment = {} do
local qmark = fullpath:find("?", 1, true)
if qmark then
path = fullpath:sub(1, qmark - 1)
local qf = fullpath:sub(qmark + 1)
local hash = qf:find("#", 1, true)
local q
if hash then q, fragment = qf:sub(1, hash - 1), qf:sub(hash)
else q, fragment = qf, ""
end
for name, value in query_args(q) do
query[name] = value
end
else
path = fullpath
fragment = ""
end
end
return setm({
request_headers = request_headers;
stream = stream,
peername = peer,
path = path,
query = query,
fragment = fragment,
method = request_headers:get":method",
headers = headers,
body = nil,
data = data,
}, mtover or response_mt)
end
function response_methods:combined_log()
return fmt('%s - - [%s] "%s %s HTTP/%g" %s %d "%s" "%s"',
self.peername or "-",
date("%d/%b/%Y:%H:%M:%S %z"),
self.request_headers:get(":method") or "",
self.request_headers:get(":path") or "",
self.stream.connection.version,
self.headers:get(":status") or "",
self.stream.stats_sent,
self.request_headers:get("referer") or "-",
self.request_headers:get("user-agent") or "-")
end
local function check_compressed(headers, raw)
if headers:get"content-encoding" == "gzip"
or headers:get"content-encoding" == "deflate"
or headers:get"content-encoding" == "x-gzip" then
return zlib.inflate()(raw, true)
end
return raw
end
function response_methods:get_body()
local bytes
if not self._receivedbody then
bytes = check_compressed(self.request_headers, self.stream:get_body_as_string())
self._receivedbody = bytes
else
bytes = self._receivedbody
end
return bytes
end
function response_methods:set_body(body)
self.body = body
local length
if typ(self.body) == "string" then
length = #body
end
if length then
self.headers:upsert("content-length", to_s(length))
end
end
function response_methods:set_503()
self.headers:upsert(":status", "503")
self.headers:upsert("content-type", TEXT)
self:set_body"Internal server error."
end
function response_methods:set_500()
self.headers:upsert(":status", "500")
self.headers:upsert("content-type", TEXT)
self:set_body"Internal server error."
end
function response_methods:set_401(msg)
self.headers:upsert(":status", "401")
self.headers:upsert("content-type", TEXT)
self:set_body(msg or "Unauthorized")
end
function response_methods:set_ok()
self.headers:upsert(":status", "204")
end
function response_methods:set_ok_and_reply(body, content_type)
self.headers:upsert(":status", "200")
self:set_body(body)
if content_type then self.headers:upsert("content-type", content_type) end
end
function response_methods:set_code_and_reply(code, body, content_type)
self.headers:upsert(":status", to_s(code))
self:set_body(body)
if content_type then self.headers:upsert("content-type", content_type) end
end
function response_methods:redirect(code_location, location)
local code = to_n(code_location)
if code then
code = (code <= 300 and code < 400) and to_s(code) or "302"
else
code = "302"
location = code_location
end
self.headers:upsert(":status", code)
self.headers:append("location", location)
return self
end
local function default_onerror(_, ...)
stderr:write('[err] ', fmt(...), "\n")
end
local function server_onerror(_, context, op, err, _)
local msg = op .. " on " .. to_s(context) .. " failed"
if err then
msg = msg .. ": " .. to_s(err)
end
write("[err] ",msg, "\n")
end
local function default_log(response)
write('[log] ', response:combined_log(), "\n")
end
local NO_ROUTES = "Please provide either a callback or mapping of callbacks to route requests."
function new(options, crtfile, keyfile)
local onerror = options.onerror or default_onerror
local log = options.log or default_log
local routes = asserts(options.routes, NO_ROUTES)
local pathed = typ(routes) == 'table'
local server_name = options.server or "shs-http-server"
options.server = nil
options.tls = nil
if options.version == nil then options.version = 1.1 end
if crtfile then
options.ctx = new_ctx(options.version, crtfile, keyfile)
options.tls = true
else
if options.ctx then
options.tls = true
else
options.tls = false
end
end
local data = options.data
local mtover = options.response_mt
local function onstream(_, stream)
local req_headers, err, errno = stream:get_headers()
if req_headers == nil then
-- connection hit EOF before headers arrived
stream:shutdown()
if err ~= ce.EPIPE and errno ~= ce.ECONNRESET then
onerror("header error: %s", to_s(err))
end
return
end
local resp = new_response(req_headers, stream, data, mtover)
resp.headers:append("server", server_name)
local ok,err2
if pathed and routes[resp.path] then
ok, err2 = try(routes[resp.path], resp)
elseif pathed and routes['*'] then
ok, err2 = try(routes['*'], resp)
elseif pathed then
resp:set_code_and_reply(404, "Not found.")
else
ok, err2 = try(routes, resp)
end
if stream.state ~= "closed" and stream.state ~= "half closed (local)" then
if not ok then
resp:set_500()
end
local send_body = resp.body and req_headers:get ":method" ~= "HEAD"
resp.headers:upsert("date", http_util.imf_date())
stream:write_headers(resp.headers, not send_body)
if send_body then
stream:write_chunk(resp.body, true)
end
end
stream:shutdown()
log(resp)
if not ok then
onerror("stream error: %s", to_s(err2))
end
end
options.onstream = onstream
options.onerror = server_onerror
local myserver = server.listen(options)
return myserver
end
_ENV.diy_tls = new_ctxlit
_ENV.response_mt = response_mt
return _ENV