2
0

cgi.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Licensed to the public under the Apache License 2.0.
  3. exectime = os.clock()
  4. module("luci.sgi.cgi", package.seeall)
  5. local ltn12 = require("luci.ltn12")
  6. require("nixio.util")
  7. require("luci.http")
  8. require("luci.sys")
  9. require("luci.dispatcher")
  10. -- Limited source to avoid endless blocking
  11. local function limitsource(handle, limit)
  12. limit = limit or 0
  13. local BLOCKSIZE = ltn12.BLOCKSIZE
  14. return function()
  15. if limit < 1 then
  16. handle:close()
  17. return nil
  18. else
  19. local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
  20. limit = limit - read
  21. local chunk = handle:read(read)
  22. if not chunk then handle:close() end
  23. return chunk
  24. end
  25. end
  26. end
  27. function run()
  28. local r = luci.http.Request(
  29. luci.sys.getenv(),
  30. limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
  31. ltn12.sink.file(io.stderr)
  32. )
  33. local x = coroutine.create(luci.dispatcher.httpdispatch)
  34. local hcache = ""
  35. local active = true
  36. while coroutine.status(x) ~= "dead" do
  37. local res, id, data1, data2 = coroutine.resume(x, r)
  38. if not res then
  39. print("Status: 500 Internal Server Error")
  40. print("Content-Type: text/plain\n")
  41. print(id)
  42. break;
  43. end
  44. if active then
  45. if id == 1 then
  46. io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
  47. elseif id == 2 then
  48. hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
  49. elseif id == 3 then
  50. io.write(hcache)
  51. io.write("\r\n")
  52. elseif id == 4 then
  53. io.write(tostring(data1 or ""))
  54. elseif id == 5 then
  55. io.flush()
  56. io.close()
  57. active = false
  58. elseif id == 6 then
  59. data1:copyz(nixio.stdout, data2)
  60. data1:close()
  61. end
  62. end
  63. end
  64. end