xrforge-v2/soakbean/middleware/cgi.lua

51 lines
1.1 KiB
Lua
Raw Normal View History

!/usr/local/bin/redlua
-- load the Unix module
local unix = require('unix')
-- load the Redbean module
local red = require('red')
-- define the allowed files
local allowed = {
"./foo",
"/bin/date",
["./foo/index.lua"] = true,
["/bin/date/index.lua"] = true
}
-- get the requested URI from the client
local uri = red.http.getenv("REQUEST_URI")
-- check if the requested URI is allowed
if allowed[uri] == nil then
allowed_uri = uri .. "/index.lua"
if allowed[allowed_uri] == nil then
-- handle 404 error
red.status(404)
red.print('404 Not Found')
return
end
uri = allowed_uri
end
-- check if the requested file is executable
if unix.access(uri, "x") then
-- execute the file and stream its output to the client
red.http.stream(function(writer)
local handle = io.popen('.' .. uri)
local chunk_size = 4096
while true do
local chunk = handle:read(chunk_size)
if chunk == nil then
break
end
writer(chunk)
end
handle:close()
end)
else
-- handle 404 error
red.status(404)
red.print('404 Not Found')
end