uhttpd.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
  2. -- Licensed to the public under the Apache License 2.0.
  3. require "nixio.util"
  4. require "luci.http"
  5. require "luci.sys"
  6. require "luci.dispatcher"
  7. require "luci.ltn12"
  8. function handle_request(env)
  9. exectime = os.clock()
  10. local renv = {
  11. CONTENT_LENGTH = env.CONTENT_LENGTH,
  12. CONTENT_TYPE = env.CONTENT_TYPE,
  13. REQUEST_METHOD = env.REQUEST_METHOD,
  14. REQUEST_URI = env.REQUEST_URI,
  15. PATH_INFO = env.PATH_INFO,
  16. SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""),
  17. SCRIPT_FILENAME = env.SCRIPT_NAME,
  18. SERVER_PROTOCOL = env.SERVER_PROTOCOL,
  19. QUERY_STRING = env.QUERY_STRING
  20. }
  21. local k, v
  22. for k, v in pairs(env.headers) do
  23. k = k:upper():gsub("%-", "_")
  24. renv["HTTP_" .. k] = v
  25. end
  26. local len = tonumber(env.CONTENT_LENGTH) or 0
  27. local function recv()
  28. if len > 0 then
  29. local rlen, rbuf = uhttpd.recv(4096)
  30. if rlen >= 0 then
  31. len = len - rlen
  32. return rbuf
  33. end
  34. end
  35. return nil
  36. end
  37. local send = uhttpd.send
  38. local req = luci.http.Request(
  39. renv, recv, luci.ltn12.sink.file(io.stderr)
  40. )
  41. local x = coroutine.create(luci.dispatcher.httpdispatch)
  42. local hcache = { }
  43. local active = true
  44. while coroutine.status(x) ~= "dead" do
  45. local res, id, data1, data2 = coroutine.resume(x, req)
  46. if not res then
  47. send("Status: 500 Internal Server Error\r\n")
  48. send("Content-Type: text/plain\r\n\r\n")
  49. send(tostring(id))
  50. break
  51. end
  52. if active then
  53. if id == 1 then
  54. send("Status: ")
  55. send(tostring(data1))
  56. send(" ")
  57. send(tostring(data2))
  58. send("\r\n")
  59. elseif id == 2 then
  60. hcache[data1] = data2
  61. elseif id == 3 then
  62. for k, v in pairs(hcache) do
  63. send(tostring(k))
  64. send(": ")
  65. send(tostring(v))
  66. send("\r\n")
  67. end
  68. send("\r\n")
  69. elseif id == 4 then
  70. send(tostring(data1 or ""))
  71. elseif id == 5 then
  72. active = false
  73. elseif id == 6 then
  74. data1:copyz(nixio.stdout, data2)
  75. end
  76. end
  77. end
  78. end