httpserver.lua 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. -- httpserver
  2. -- Author: Marcos Kirsch
  3. module("httpserver", package.seeall)
  4. -- Functions below aren't part of the public API
  5. -- Clients don't need to worry about them.
  6. -- given an HTTP method, returns it or if invalid returns nil
  7. local function validateMethod(method)
  8. local httpMethods = {GET=true, HEAD=true, POST=true, PUT=true, DELETE=true, TRACE=true, OPTIONS=true, CONNECT=true, PATCH=true}
  9. if httpMethods[method] then return method else return nil end
  10. end
  11. local function parseRequest(request)
  12. local e = request:find("\r\n", 1, true)
  13. if not e then return nil end
  14. local line = request:sub(1, e - 1)
  15. local r = {}
  16. _, i, r.method, r.uri = line:find("^([A-Z]+) (.-) HTTP/[1-9]+.[1-9]+$")
  17. return r
  18. end
  19. local function uriToFilename(uri)
  20. return "http/" .. string.sub(uri, 2, -1)
  21. end
  22. local function parseArgs(args)
  23. local r = {}; i=1
  24. if args == nil or args == "" then return r end
  25. for arg in string.gmatch(args, "([^&]+)") do
  26. local name, value = string.match(arg, "(.*)=(.*)")
  27. if name ~= nil then r[name] = value end
  28. i = i + 1
  29. end
  30. return r
  31. end
  32. local function parseUri(uri)
  33. local r = {}
  34. if uri == nil then return r end
  35. if uri == "/" then uri = "/index.html" end
  36. questionMarkPos, b, c, d, e, f = uri:find("?")
  37. if questionMarkPos == nil then
  38. r.file = uri:sub(1, questionMarkPos)
  39. r.args = {}
  40. else
  41. r.file = uri:sub(1, questionMarkPos - 1)
  42. r.args = parseArgs(uri:sub(questionMarkPos+1, #uri))
  43. end
  44. _, r.ext = r.file:match("(.+)%.(.+)")
  45. r.isScript = r.ext == "lua" or r.ext == "lc"
  46. r.file = uriToFilename(r.file)
  47. return r
  48. end
  49. -- This variable holds the thread used for sending data back to the user.
  50. -- We do it in a separate thread because we need to yield when sending lots
  51. -- of data in order to avoid overflowing the mcu's buffer.
  52. local connectionThread
  53. local function onGet(connection, uri)
  54. local uri = parseUri(uri)
  55. local fileExists = file.open(uri.file, "r")
  56. file.close()
  57. local fileServeFunction = nil
  58. if not fileExists then
  59. uri.args['code'] = 404
  60. fileServeFunction = dofile("httpserver-error.lc")
  61. elseif uri.isScript then
  62. collectgarbage()
  63. fileServeFunction = dofile(uri.file)
  64. else
  65. uri.args['file'] = uri.file
  66. uri.args['ext'] = uri.ext
  67. fileServeFunction = dofile("httpserver-static.lc")
  68. end
  69. connectionThread = coroutine.create(fileServeFunction)
  70. coroutine.resume(connectionThread, connection, uri.args)
  71. end
  72. local function onReceive(connection, payload)
  73. --print(payload) -- for debugging
  74. -- parse payload and decide what to serve.
  75. local req = parseRequest(payload)
  76. print("Requested URI: " .. req.uri)
  77. req.method = validateMethod(req.method)
  78. if req.method == "GET" then onGet(connection, req.uri)
  79. elseif req.method == nil then dofile("httpserver-static.lc")(conection, {code=400})
  80. else dofile("httpserver-static.lc")(conection, {code=501}) end
  81. end
  82. local function onSent(connection, payload)
  83. if coroutine.status(connectionThread) == "dead" then
  84. -- We're done sending file.
  85. connection:close()
  86. connectionThread = nil
  87. elseif coroutine.status(connectionThread) == "suspended" then
  88. -- Not finished sending file, resume.
  89. coroutine.resume(connectionThread)
  90. else
  91. print ("Fatal error! I did not expect to hit this codepath")
  92. connection:close()
  93. end
  94. end
  95. local function handleRequest(connection)
  96. connection:on("receive", onReceive)
  97. connection:on("sent", onSent)
  98. end
  99. -- Starts web server in the specified port.
  100. return function (port)
  101. local s = net.createServer(net.TCP, 10) -- 10 seconds client timeout
  102. s:listen(port, handleRequest)
  103. print("nodemcu-httpserver running at http://" .. wifi.sta.getip() .. ":" .. port)
  104. return s
  105. end