Artifact Content

Artifact a95c96a03f08cff695ccc8ce44422aa99f8cb0011a884988c34f12a13e1a1eff:


-- dynamic lua hypertext
-- example browse - introduction
-- see dlh.conf.lua and server_control.dlh
-- DON'T USE that dlh it's a simple EXAMPLE ONLY
-- It is insecure, because it shows all the files in the directory (including it's source)
-- It accepts untested file uploads
-- It will fill up the ram with sending big files, shouldn't be loaded in one chunk

MEDIA_TYPE_PLAIN = {adoc = true, info = true, nfo = true, md = true, txt = true}
-- log contains functions for every defined level (see config)
-- request = {
--   method -> (string.upper() GET HEAD POST)
--   http_version
--   remote_ip -> if supported and behind proxy "127.0.0.1"
--   home -> here is the script, helpful for includes
--   header -> header[string.lower("Content-Length")], header.host, ..
--   cookie
--   arg -> [-1] => dlh_id, [0] => script path, 1..n further elements
--     -> example: /browse/open/file.adoc -> {[-1] = "/browse/*", [0] = "/browse", "open", "file.adoc"
--   data -> GET/POST form data (key = value or file_name = {{filename, tmpname, content-type},}
-- }
-- response = {
--   getStatus() -> returns number current status code, string status and string location (if set)
--     -> for creating a custom (404, 302, ..) status page
--   setStatus(number[, string location]) -> change the return status and set location
--   setHeader(string key, string value)
--     -> set "transfer-encoding" to chunked, for chunked writing
--   setCookie(string)
--   write(format string[, ..])
-- }

if request.method == "POST" then
-- upload file
  local upfile = request.data.uploaded_file[1]
  os.execute(string.format("cp %s %s/%s", upfile.tmpname, request.home, upfile.filename or "uploaded_file"))
elseif request.arg[1] then
-- download file
  local file_body = io.open(string.format("%s/%s", request.home, request.arg[1]))
  if not(file_body) then
    response.setStatus(404)
    return
  end
  -- ! this will KILL the RAM with a big files
  local body = file_body:read("a")
  file_body:close()
  local media_type = "application/octetstream"
  local suffix = string.match(request.arg[1], ".*%.([^.]*)$", -4)
  if suffix == "html" then
    media_type = "text/html"
  elseif MEDIA_TYPE_PLAIN[suffix] then
    media_type = "text/plain"
  end
  response.setHeader("content-type", media_type)
  response.write(body)
  return
end
-- list directory
response.write("<!DOCTYPE html><html><head><title>Browse</title></head><body><h1>Browse</h1><p>")
local directory = io.popen(string.format("ls %s", request.home))
for filename in directory:lines() do
  response.write("<a href='%s/%s'>%s</a><br/>", request.arg[0], filename, filename)
end
directory:close()
response.write("</p><form action='%s' method='post'><p>", request.arg[0])
response.write("<input type='file' name='uploaded_file'/><input type='submit' name='submit' value='upload'/>")
response.write("</p></form></body></html>")