httpserver.lua 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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]+.[0-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. -- Starts web server in the specified port.
  50. return function (port)
  51. local s = net.createServer(net.TCP, 10) -- 10 seconds client timeout
  52. s:listen(
  53. port,
  54. function (connection)
  55. -- This variable holds the thread used for sending data back to the user.
  56. -- We do it in a separate thread because we need to yield when sending lots
  57. -- of data in order to avoid overflowing the mcu's buffer.
  58. local connectionThread
  59. local function onGet(connection, uri)
  60. local uri = parseUri(uri)
  61. local fileServeFunction = nil
  62. if #(uri.file) > 32 then
  63. -- nodemcu-firmware cannot handle long filenames.
  64. uri.args['code'] = 400
  65. fileServeFunction = dofile("httpserver-error.lc")
  66. else
  67. local fileExists = file.open(uri.file, "r")
  68. file.close()
  69. if not fileExists then
  70. uri.args['code'] = 404
  71. fileServeFunction = dofile("httpserver-error.lc")
  72. elseif uri.isScript then
  73. collectgarbage()
  74. fileServeFunction = dofile(uri.file)
  75. else
  76. uri.args['file'] = uri.file
  77. uri.args['ext'] = uri.ext
  78. fileServeFunction = dofile("httpserver-static.lc")
  79. end
  80. end
  81. connectionThread = coroutine.create(fileServeFunction)
  82. --print("Thread created", connectionThread)
  83. coroutine.resume(connectionThread, connection, uri.args)
  84. end
  85. local function onReceive(connection, payload)
  86. --print(payload) -- for debugging
  87. -- parse payload and decide what to serve.
  88. local req = parseRequest(payload)
  89. print("Requested URI: " .. req.uri)
  90. req.method = validateMethod(req.method)
  91. if req.method == "GET" then onGet(connection, req.uri)
  92. elseif req.method == nil then dofile("httpserver-static.lc")(conection, {code=400})
  93. else dofile("httpserver-static.lc")(conection, {code=501}) end
  94. end
  95. local function onSent(connection, payload)
  96. local connectionThreadStatus = coroutine.status(connectionThread)
  97. -- print (connectionThread, "status is", connectionThreadStatus)
  98. if connectionThreadStatus == "suspended" then
  99. -- Not finished sending file, resume.
  100. -- print("Resume thread", connectionThread)
  101. coroutine.resume(connectionThread)
  102. elseif connectionThreadStatus == "dead" then
  103. -- We're done sending file.
  104. -- print("Done thread", connectionThread)
  105. connection:close()
  106. connectionThread = nil
  107. end
  108. end
  109. connection:on("receive", onReceive)
  110. connection:on("sent", onSent)
  111. end
  112. )
  113. print("nodemcu-httpserver running at http://" .. wifi.sta.getip() .. ":" .. port)
  114. return s
  115. end