forked from kibook/httpmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httphandler.lua
553 lines (420 loc) · 10.6 KB
/
httphandler.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
local mainResourceName = GetCurrentResourceName()
-- Default options for new HTTP handlers
local defaultOptions = {
documentRoot = "http",
directoryIndex = "index.html",
templateExtension = "lsp",
access = {},
log = false,
logFile = "log.json",
errorPages = {},
mimeTypes = {},
routes = {}
}
-- The size of each block used when reading a file on disk
local blockSize = 131072
-- Maximum number of bytes to send in one ranged response
local maxContentLength = 5242880
local function createHttpHandler(options)
local resourceName = GetInvokingResource() or GetCurrentResourceName()
local resourcePath = GetResourcePath(resourceName)
if type(options) ~= "table" then
options = {}
end
for key, defaultValue in pairs(defaultOptions) do
if options[key] == nil then
options[key] = defaultValue
end
end
local handlerLog
if options.log then
handlerLog = json.decode(LoadResourceFile(resourceName, options.logFile)) or {}
end
local authorizations = {}
local realm
if type(options.authorization) == "string" then
realm = options.authorization
options.authorization = Realms[realm] or {}
else
realm = resourceName
end
local function getExtension(path)
return path:match("^.+%.(.+)$")
end
local function getMimeType(path)
local extension = getExtension(path)
if options.mimeTypes[extension] then
return options.mimeTypes[extension]
elseif MimeTypes[extension] then
return MimeTypes[extension]
else
return "application/octet-stream"
end
end
local function parseTemplate(content, name, env)
if type(env) ~= "table" then
env = {}
end
for k, v in pairs(_G) do
if env[k] == nil then
env[k] = v
end
end
local parsed = content
parsed = parsed:gsub("(%%%b{})", function(w)
local fn, err = load(w:sub(3, -2), name, "t", env)
if fn then
local status, res = pcall(fn)
return res or ""
else
return err
end
end)
parsed = parsed:gsub("($%b{})", function(w)
local fn, err = load("return (" .. w:sub(3, -2) .. ")", nil, "t", env)
if fn then
local status, res = pcall(fn)
return res or ""
else
return err
end
end)
return parsed
end
local function sendError(req, res, code, details, headers)
if not code then
code = 500
end
if details == nil then
details = false
end
if type(headers) ~= "table" then
headers = {}
end
if not headers["Content-Type"] then
headers["Content-Type"] = "text/html"
end
res.writeHead(code, headers)
if req.method == "HEAD" then
res.send()
else
local resource, path
if options.errorPages[code] then
resource = resourceName
path = options.documentRoot .. "/" .. options.errorPages[code]
else
resource = mainResourceName
path = defaultOptions.documentRoot .. "/" .. code .. ".html"
end
local data = LoadResourceFile(resource, path)
if data then
res.send(parseTemplate(data, path, {details = details}))
else
if details then
res.send("Error: " .. code .. ": " .. details)
else
res.send("Error: " .. code)
end
end
end
end
local function log(entry)
if not handlerLog then
return
end
entry.time = os.time()
table.insert(handlerLog, entry)
table.sort(handlerLog, function(a, b)
return a.time < b.time
end)
SaveResourceFile(resourceName, options.logFile, json.encode(handlerLog), -1)
end
local function sendTemplate(req, res, content, name, env, code, headers)
if type(env) ~= "table" then
env = {}
end
env.request = req
if not code then
code = 200
end
if type(headers) ~= "table" then
headers = {}
end
if not headers["Content-Type"] then
headers["Content-Type"] = "text/html"
end
local parsed = parseTemplate(content, name, env)
res.writeHead(code, headers)
res.send(parsed)
end
local function getAbsolutePath(path)
if path:sub(1, 1) ~= "/" then
path = "/" .. path
end
return resourcePath .. "/" .. options.documentRoot .. path
end
local function sendTemplateFile(req, res, path, env, code, headers)
local absolutePath = getAbsolutePath(path)
local f = io.open(absolutePath, "rb")
if f then
local content = f:read("*all")
f:close()
sendTemplate(req, res, content, path, env, code, headers)
else
sendError(req, res, 404)
end
end
local function sendFile(req, res, path)
local absolutePath = getAbsolutePath(path)
local mimeType = getMimeType(absolutePath)
local f = io.open(absolutePath, "rb")
local statusCode
if f then
local startBytes, endBytes
if req.headers.Range then
startBytes = tonumber(req.headers.Range:match("^bytes=(%d+)-.*$"))
endBytes = tonumber(req.headers.Range:match("^bytes=%d+-(%d+)$"))
end
if not startBytes or startBytes < 0 then
startBytes = 0
end
local fileSize = f:seek("end")
f:seek("set", startBytes)
if not endBytes then
if req.headers.Range then
endBytes = math.min(startBytes + maxContentLength, fileSize) - 1
else
endBytes = fileSize - 1
end
end
local headers = {
["Content-Type"] = mimeType,
["Transfer-Encoding"] = "identity",
["Accept-Ranges"] = "bytes"
}
if startBytes > 0 or endBytes < fileSize - 1 then
statusCode = 206
headers["Content-Range"] = ("bytes %d-%d/%d"):format(startBytes, endBytes, fileSize)
headers["Content-Length"] = tostring(endBytes - startBytes + 1)
else
statusCode = 200
headers["Content-Length"] = tostring(fileSize)
end
res.writeHead(statusCode, headers)
Citizen.CreateThread(function()
if req.method ~= "HEAD" then
local cancelled = false
req.setCancelHandler(function()
cancelled = true
end)
while not cancelled do
if startBytes > endBytes then
break
end
local block = f:read(blockSize)
if not block then
break
end
res.write(block)
startBytes = startBytes + blockSize
Citizen.Wait(0)
end
end
res.send()
f:close()
end)
else
statusCode = 404
sendError(req, res, statusCode)
end
log {
type = "file",
path = req.path,
address = req.address,
method = req.method,
headers = req.headers,
status = statusCode,
file = absolutePath
}
return statusCode
end
local function readBody(req)
local p = promise.new()
req.setDataHandler(function(body)
p:resolve(body)
end)
return p
end
local function readJson(req)
local p = promise.new()
req.setDataHandler(function(body)
local data = json.decode(body)
if data == nil then
p:reject("Request body contains invalid JSON")
else
p:resolve(data)
end
end)
return p
end
local function sendJson(req, res, data, code, headers)
if not code then
code = 200
end
if type(headers) ~= "table" then
headers = {}
end
if not headers["Content-Type"] then
headers["Content-Type"] = "application/json"
end
res.writeHead(code, headers)
if req.method == "HEAD" then
res.send()
else
if type(data) == "string" then
res.send(data)
else
res.send(json.encode(data))
end
end
end
local function isAuthorized(req, path)
local login
for i = #options.access, 1, -1 do
if path:match(options.access[i].path) then
login = options.access[i].login
break
end
end
if login == false then
return true
end
local auth = req.headers.Authorization
if not auth then
return false
end
local encoded = auth:match("^Basic (.+)$")
if not encoded then
return false
end
local decoded = base64.decode(encoded)
local username, password = decoded:match("^([^:]+):(.+)$")
if not (username and password) then
return false
end
if login and not login[username] then
return false
end
req.user = username
if authorizations[auth] then
return true
end
if not options.authorization[username] then
return false
end
if not verifyPassword(password, options.authorization[username]) then
return false
end
authorizations[auth] = true
return true
end
return function(req, res)
local url = Url.normalize(req.path)
req.url = url
if options.authorization and not isAuthorized(req, url.path) then
sendError(req, res, 401, "Invalid login for realm: " .. realm, {
["WWW-Authenticate"] = ("Basic realm=\"%s\""):format(realm)
})
return
end
for pattern, callback in pairs(options.routes) do
local matches = {url.path:match(pattern)}
if #matches > 0 then
req.readBody = function()
return readBody(req)
end
req.readJson = function()
return readJson(req)
end
res.sendError = function(code, details, headers)
sendError(req, res, code, details, headers)
end
res.sendFile = function(path)
sendFile(req, res, path)
end
res.sendJson = function(data, code, headers)
sendJson(req, res, data, code, headers)
end
res.sendTemplate = function(content, env, code, headers)
sendTemplate(req, res, content, url.path, env, code, headers)
end
res.sendTemplateFile = function(path, env, code, headers)
sendTemplateFile(req, res, path, env, code, headers)
end
local helpers = {
log = function(entry)
entry.type = "message"
entry.route = pattern
log(entry)
end
}
callback(req, res, helpers, table.unpack(matches))
log {
type = "route",
route = pattern,
path = req.path,
address = req.address,
method = req.method,
headers = req.headers,
}
return
end
end
if options.documentRoot then
if url.path:sub(-1) == "/" then
url.path = url.path .. options.directoryIndex
end
local extension = getExtension(url.path)
if extension == options.templateExtension then
sendTemplateFile(req, res, url.path)
else
sendFile(req, res, url.path)
end
else
sendError(req, res, 404, "No route matches " .. url)
end
end
end
exports("createHttpHandler", createHttpHandler)
exports("getUrl", function(resourceName)
local baseUrl = GetConvar("web_baseUrl", "")
local protocol, endpoint
if baseUrl == "" then
protocol = "http"
endpoint = "[server IP]:[server port]"
else
protocol = "https"
endpoint = baseUrl
end
if not resourceName then
resourceName = GetInvokingResource() or mainResourceName
end
return ("%s://%s/%s/"):format(protocol, endpoint, resourceName)
end)
-- Apply inheritance for realms
for realm, users in pairs(Realms) do
if users.inherit and Realms[users.inherit] then
local inheritedRealms
if type(users.inherit) == "table" then
inheritedRealms = users.inherit
else
inheritedRealms = {users.inherit}
end
for _, inheritedRealm in ipairs(inheritedRealms) do
for username, password in pairs(Realms[inheritedRealm]) do
users[username] = password
end
end
users.inherit = nil
end
end