httpserver.lua 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. -- 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 fileExists = file.open(uri.file, "r")
  62. file.close()
  63. local fileServeFunction = nil
  64. if not fileExists then
  65. uri.args['code'] = 404
  66. fileServeFunction = dofile("httpserver-error.lc")
  67. elseif uri.isScript then
  68. collectgarbage()
  69. fileServeFunction = dofile(uri.file)
  70. else
  71. uri.args['file'] = uri.file
  72. uri.args['ext'] = uri.ext
  73. fileServeFunction = dofile("httpserver-static.lc")
  74. end
  75. connectionThread = coroutine.create(fileServeFunction)
  76. --print("Thread created", connectionThread)
  77. coroutine.resume(connectionThread, connection, uri.args)
  78. end
  79. local function onReceive(connection, payload)
  80. --print(payload) -- for debugging
  81. -- parse payload and decide what to serve.
  82. local req = parseRequest(payload)
  83. print("Requested URI: " .. req.uri)
  84. req.method = validateMethod(req.method)
  85. if req.method == "GET" then onGet(connection, req.uri)
  86. elseif req.method == nil then dofile("httpserver-static.lc")(conection, {code=400})
  87. else dofile("httpserver-static.lc")(conection, {code=501}) end
  88. end
  89. local function onSent(connection, payload)
  90. local connectionThreadStatus = coroutine.status(connectionThread)
  91. --print (connectionThread, "status is", connectionThreadStatus)
  92. if connectionThreadStatus == "dead" then
  93. -- We're done sending file.
  94. --print("Done sending file", connectionThread)
  95. connection:close()
  96. connectionThread = nil
  97. elseif connectionThreadStatus == "suspended" then
  98. -- Not finished sending file, resume.
  99. --print("Resume thread", connectionThread)
  100. coroutine.resume(connectionThread)
  101. else
  102. print ("Fatal error! I did not expect to hit this codepath")
  103. connection:close()
  104. end
  105. end
  106. connection:on("receive", onReceive)
  107. connection:on("sent", onSent)
  108. end
  109. )
  110. print("nodemcu-httpserver running at http://" .. wifi.sta.getip() .. ":" .. port)
  111. return s
  112. end